iOS 中的 JSON 请求 - 使用 Grand Central Dispatch 或 NSURLConnection

Posted

技术标签:

【中文标题】iOS 中的 JSON 请求 - 使用 Grand Central Dispatch 或 NSURLConnection【英文标题】:JSON requests in iOS - use Grand Central Dispatch or NSURLConnection 【发布时间】:2013-03-23 20:13:18 【问题描述】:

我看到了一些关于在 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);
);

哪个更好用?后者的简单性是否存在固有的错误?

【问题讨论】:

第二个更简单,可能更难搞砸,尤其是当你处理大量请求时。不像第一个那样灵活。 【参考方案1】:

使用stringWithContentsOfURL:encoding:error: 没有任何“错误”,但您在处理正在进行的请求方面没有灵活性。如果您需要执行以下任何操作,那么我会使用NSURLConnection

    在请求期间向用户显示完成百分比 向需要 HTTP 身份验证的主机执行请求 更复杂的数据处理(例如,下载比来自 Web 服务的典型 JSON 响应更多的数据),您可能希望以块的形式处理响应 取消请求(感谢@martin)

【讨论】:

4.您可以取消请求。【参考方案2】:

使用第一个。您有一个方法可以告诉您连接何时完成,然后您可以执行另一种方法来显示数据或您打算对其进行的任何操作。

【讨论】:

stringWithContentsOfURL:encoding:error: 是同步的,所以当它返回时请求就完成了。然后,您可以向主线程发布通知以在 UI 中显示结果。不过,我更喜欢NSURLConnection 还有其他原因。 确实,你可以这样做,但是使用委托方法构建的东西更简单,让你知道何时完成。

以上是关于iOS 中的 JSON 请求 - 使用 Grand Central Dispatch 或 NSURLConnection的主要内容,如果未能解决你的问题,请参考以下文章

北京化工大学第17届程序设计竞赛 - 女生赛 - 2022.08.28 - 问题 A: You love JSON. Aren‘t you?

AtCoder Grand Contest 039

AtCoder Grand Contest 039 F: Min Product Sum

AtCoder Grand Contest 039 F: Min Product Sum

如何使用android studio中的改造服务在请求中传递json

AtCoder Grand Contest 043(坑)