当我使用NSData时如何处理连接问题? [英] How can I deal with connection problem when I use NSData?

查看:280
本文介绍了当我使用NSData时如何处理连接问题?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

One init method of NSXMLParser is initWithData:(NSData *data). When I init the NSData like this,

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

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

if the IP address cannot be reached, my app will wait for that address's response forever.

如何解决这个问题?

谢谢!

推荐答案

网址加载系统编程指南。这应该给你一个提示;该指南有更完整的示例代码:

You will have to get the data through a NSURLConnection, which will have a timeout value, as described in the URL Loading System Programming Guide. This should give you a hint; the guide has more complete sample code:

// 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的类参考你可能最感兴趣的连接:didRecieveData connection:didFailWithError:

Delegate methods are described in the NSURLConnection Class Reference You are probably most interested in connection:didRecieveData and connection:didFailWithError:

这篇关于当我使用NSData时如何处理连接问题?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆