iOS中的JSON请求-使用Grand Central Dispatch或NSURLConnection [英] JSON requests in iOS - use Grand Central Dispatch or NSURLConnection
问题描述
我看到了一些有关在iOS中进行JSON请求的教程,其中许多教程都使用NSURLConnection列出了类似的内容:
I saw several tutorials on making JSON requests in iOS, many of them listed something like this using 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/)在此实现了非常简单的实现:
But I read another tutorial today (http://mobile.tutsplus.com/tutorials/iphone/ios-quick-tip-interacting-with-web-services/) where it had this beautifully simple implementation:
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);
});
哪个会更好?后者的简单性有天生的错误吗?
Which one would be better to use? Is there one inherently wrong with the simplicity of the latter?
推荐答案
使用stringWithContentsOfURL:encoding:error:
并没有什么错",但是您在处理正在进行的请求时没有灵活性.如果您需要执行以下任一操作,则可以使用NSURLConnection
:
There is nothing "wrong" with the using stringWithContentsOfURL:encoding:error:
but you have no flexibility in how you handle a request in progress. If you need to do any of the following then I would use NSURLConnection
:
- 在请求期间向用户显示完成百分比
- 向需要HTTP身份验证的主机执行请求
- 更复杂的数据处理(例如,从Web服务下载的数据比典型的JSON响应要多),您可能需要分块处理响应
- 取消请求(感谢@martin)
这篇关于iOS中的JSON请求-使用Grand Central Dispatch或NSURLConnection的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!