我有一個類用於從我的服務器獲取數據。從我的服務器返回的數據是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放在一個類中呢? –
因爲上面的代碼會在我的應用程序中多次使用,這就是爲什麼我將它放在類中 –