我有一个类用于从我的服务器获取数据。从我的服务器返回的数据是JSON。出于某种原因,didReceiveData根本无法运行。我已经将NSLog放入它来测试它,但它没有做任何事情?为什么didReceiveData函数不能正常工作
这里是我的代码:
+(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:'方法返回接收到的JSON,因为NSURLConnection *异步*工作。 - 也许你从'getTask:'返回后取消连接? –
我不确定。那么我怎样才能把NSURLConnection放在一个类中呢? –
因为上面的代码会在我的应用程序中多次使用,这就是为什么我将它放在类中 –