【问题标题】:How can I deal with connection problem when I use NSData?使用 NSData 时如何处理连接问题?
【发布时间】:2011-07-21 01:51:59
【问题描述】:

NSXMLParser 的一个 init 方法是 initWithData:(NSData *data)。 当我像这样初始化 NSData 时,

NSURL *url = [NSURL URLWithString:@"http://221.34.21.9"];
NSData *date = [[NSData alloc] initWithContentsOfURL:url];

如果无法访问 IP 地址, 我的应用将永远等待该地址的响应。

我该如何解决这个问题?

谢谢!

【问题讨论】:

    标签: objective-c cocoa nsdata nsurl


    【解决方案1】:

    您需要从Apple Reaceability example 实施 Internet 可达性。 这是一项测试,可让您知道您的互联网连接是否可达。

    【讨论】:

      【解决方案2】:

      您必须通过NSURLConnection 获取数据,该NSURLConnection 将具有超时值,如URL Loading System Programming Guide 中所述。这应该给你一个提示;该指南有更完整的示例代码:

      // Create an NSURLRequest object with your desired URL and timeout value
      NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:@"http://221.34.21.9"]
                                cachePolicy:NSURLRequestUseProtocolCachePolicy
                            timeoutInterval:15.0];
      // Begin a connection using that request
      // Assign a delegate object that will get callbacks when things happen
      NSURLConnection *connection = [[NSURLConnection alloc] initWithRequest:request delegate:self];
      

      NSURLConnection Class Reference 中描述了委托方法,您可能对connection:didRecieveDataconnection:didFailWithError: 最感兴趣

      【讨论】:

      • 非常感谢。很有帮助!
      猜你喜欢
      • 2013-03-14
      • 2012-12-30
      • 1970-01-01
      • 1970-01-01
      • 2013-07-31
      • 2013-02-19
      • 1970-01-01
      • 1970-01-01
      • 2015-04-01
      相关资源
      最近更新 更多