我有一个用于从服务器获取数据的类。我的服务器返回的数据是JSON。由于某些原因,didReceiveData根本不会运行。我已经在其中放置了NSLogs进行测试,但是它什么也没做?
这是我的代码:
+(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);
}
谢谢,
彼得
最佳答案
getTask:
是一个类方法,这意味着self
是该类。因此,委托方法也必须是类方法。
但是请注意,您无法从getTask:
方法返回接收到的JSON,因为NSURLConnection
是异步工作的。
关于ios - 为什么didReceiveData函数不起作用,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/22051715/