为什么didReceiveData函数不起作用

时间:2014-02-26 19:47:19

标签: ios objective-c class nsurlconnection

我有一个用于从我的服务器获取数据的类。从我的服务器返回的数据是JSON。由于某种原因,didReceiveData根本不会运行。我已经在其中放置了NSLog来测试它,但它没有做任何事情?

这是我的代码:

+(NSJSONSerialization *) getTask:(id)task_id{

    NSString *post = [NSString stringWithFormat:@"&task_id=%@", task_id];

    NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];
    NSString *postLength = [NSString stringWithFormat:@"%lu",(unsigned long)[postData length]];
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:[NSString stringWithFormat:@"http://my-server.com/"]]];
    [request setHTTPMethod:@"POST"];
    [request setValue:postLength forHTTPHeaderField:@"Content-Length"];
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Current-Type"];
    [request setHTTPBody:postData];

    NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self];

    if(conn){
        NSLog(@"Testing");
    }

    return json;
}

// Log the response for debugging
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData*)data {
    NSLog(@"test");
    NSString *jsonString = [[NSString alloc] initWithData:data encoding:NSUTF8StringEncoding];
    NSData *jsonData = [jsonString dataUsingEncoding:NSUTF8StringEncoding];
    json = [NSJSONSerialization JSONObjectWithData:jsonData options:0 error:nil];
}

// Declare any connection errors
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    NSLog(@"Error: %@", error);
}

谢谢,

彼得

2 个答案:

答案 0 :(得分:3)

getTask:是一个类方法,这意味着self是类。因此委托方法也必须是类方法。

但请注意,您无法从getTask:方法返回收到的JSON,因为NSURLConnection异步工作。

答案 1 :(得分:1)

您需要开始连接。尝试使用initWithRequest:delegate:startImmediately:方法:

NSURLConnection *conn = [[NSURLConnection alloc]initWithRequest:request delegate:self startImmediately:YES];

或者,只需调用start方法:

if(conn){
    [conn start];
}