问题
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