iOS中的JSON请求 – 使用Grand Central Dispatch或NSURLConnection
我在iOS上看到了几个关于制作JSON请求的教程,其中许多使用NSURLConnection列出了这样的东西:
- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { [self.responseData setLength:0]; } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data { [self.responseData appendData:data]; } - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { NSLog([NSString stringWithFormat:@"Connection failed: %@", [error description]]); } - (void)connectionDidFinishLoading:(NSURLConnection *)connection {}
但我今天阅读了另一个教程( http://mobile.tutsplus.com/tutorials/iphone/ios-quick-tip-interacting-with-web-services/ ),其中有一个非常简单的实现:
dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0); dispatch_async(queue, ^{ NSError *error = nil; NSURL *url = [NSURL URLWithString:@"http://brandontreb.com/apps/pocket-mud-pro/promo.json"]; NSString *json = [NSString stringWithContentsOfURL:url encoding:NSASCIIStringEncoding error:&error]; NSLog(@"\nJSON: %@ \n Error: %@", json, error); });
哪一个会更好用? 后者的简单性是否存在一个固有的错误?
使用stringWithContentsOfURL:encoding:error:
没有“错误” stringWithContentsOfURL:encoding:error:
但是您在处理正在进行的请求方面没有灵活性。 如果您需要执行以下任何操作,那么我将使用NSURLConnection
:
- 在请求期间向用户显示完成百分比
- 向需要HTTP身份validation的主机执行请求
- 更复杂的数据处理(例如,下载比Web服务的典型JSON响应更多的数据),您可能希望以块的forms处理响应
- 取消请求(感谢@martin)
使用第一个。 您有一个方法可以告诉您连接何时完成,然后您可以执行另一种方法来显示数据或您计划使用它做什么。