0

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!

jscs
  • 63,694
  • 13
  • 151
  • 195
Jerry
  • 35
  • 5

2 Answers2

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:

jscs
  • 63,694
  • 13
  • 151
  • 195
0

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.

Oleg Danu
  • 4,149
  • 4
  • 29
  • 47