iPhone Web service Request Timeout

2019-08-01 05:20发布

问题:

I am having problems in my iphone application due to weak wifi signals. My application uses webservice to retireve data from our server but when Wifi signals are weak the response never comes back and user gets stuck on "Loading..." overlay screen. Finally the application crashes at the end. How can i handle this situation gracefully. Is there a way to set TimeOut for my webservice calls or something like this?

Thanks, Asif.

回答1:

try to use ASIHTTP lib

http://allseeing-i.com/ASIHTTPRequest/How-to-use



回答2:

You might want to learn about ASIHTTPRequest as it features much more than the standard CFNetwork api. The code is straight forward, error handling as well:

- (IBAction)grabURLInBackground:(id)sender
{
   NSURL *url = [NSURL URLWithString:@"http://allseeing-i.com"];
   ASIHTTPRequest *request = [ASIHTTPRequest requestWithURL:url];
   [request setDelegate:self];
   [request startAsynchronous];
}

- (void)requestFinished:(ASIHTTPRequest *)request
{
   // Use when fetching text data
   NSString *responseString = [request responseString];

   // Use when fetching binary data
   NSData *responseData = [request responseData];
}

- (void)requestFailed:(ASIHTTPRequest *)request
{
   NSError *error = [request error];
}


回答3:

You can set the NSURLConnection timeout and a delegate to respond to connection:didFailWithError: selector. See this S.O. topic.

if your delegate is never being called, this is a somehow known issue. The only workaround seems to be setting your own NSTimer to fire after some time and cancel the request. It is definitely awkard, but it should not be that complex.

If you are curious about the reason behind the issue with timeout, it seems to be related to the slow starting of the 3G subsystem in an iPhone.