How can I deal with connection problem when I use NSData?

南楼画角 提交于 2019-12-11 23:48:34

问题


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];

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

How can I solve this problem?

Thanks!


回答1:


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];

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




回答2:


You need to implement Internet Reacheability, from Apple Reaceability example. It is a test which will allow you to know if your internet connection is reachable.



来源:https://stackoverflow.com/questions/5401708/how-can-i-deal-with-connection-problem-when-i-use-nsdata

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!