【问题标题】:JSON requests in iOS - use Grand Central Dispatch or NSURLConnectioniOS 中的 JSON 请求 - 使用 Grand Central Dispatch 或 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);
});

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

【问题讨论】:

  • 第二个更简单,可能更难搞砸,尤其是当你处理大量请求时。不像第一个那样灵活。

标签: ios objective-c xcode json


【解决方案1】:

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

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

【讨论】:

  • 4.您可以取消请求。
【解决方案2】:

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

【讨论】:

  • stringWithContentsOfURL:encoding:error: 是同步的,所以当它返回时请求就完成了。然后,您可以向主线程发布通知以在 UI 中显示结果。不过,我更喜欢NSURLConnection 还有其他原因。
  • 确实,你可以这样做,但是使用委托方法构建的东西更简单,让你知道何时完成。
猜你喜欢
  • 1970-01-01
  • 2011-06-04
  • 1970-01-01
  • 1970-01-01
  • 2012-05-09
  • 1970-01-01
  • 2012-10-18
  • 1970-01-01
相关资源
最近更新 更多