Shemil Hashan
Shemil Hashan

Reputation: 67

How to check a timeout occurred in ios url connection?

I have used URLRequest to fetch a html file from a pc in my wifi network. My app fetches a html file from my fileserver and the filename is a number which is typed in the app. Also I have given a 20 seconds timeout for the request. How can I detect whether timeout occurred because I have 2 situations, 1. file does not exist 2. connection is slow

In urlrequest, there is a BOOL for error,no description. Suggest me a method if possible. My code is below for only urlrequest

-(void)getHtmlContent{
[self.spinner startAnimating];
NSString *str = @"http://192.168.1.250/rec/";
//        NSString *str = @"file:///Volumes/xampp/htdocs/";
str = [str stringByAppendingString:numEntered.text];
str = [str stringByAppendingString:@".html"];
NSURL *url=[NSURL URLWithString:str];
//self.htmlContent = nil;

NSMutableURLRequest *request = [NSMutableURLRequest             requestWithURL:url];
    //NSURLRequest *request = [NSURLRequest requestWithURL:url];
    request.timeoutInterval = 20.0;
    NSURLSessionConfiguration *configuration = [NSURLSessionConfiguration ephemeralSessionConfiguration];
    NSURLSession *session = [NSURLSession sessionWithConfiguration:configuration];
    NSURLSessionDownloadTask *task = [session downloadTaskWithRequest:request completionHandler:^(NSURL *localfile, NSURLResponse *response, NSError *error) {
        if(!error){
            if([request.URL isEqual:url]){

                NSString *content = [NSString stringWithContentsOfURL:localfile encoding: NSUTF8StringEncoding error:&error];
                dispatch_async(dispatch_get_main_queue(), ^{
                    [numEntered setText:@"0"];
                    text = @"";
                    [self.spinner stopAnimating];

                    self.htmlContent = content;

                    NSString *myHTMLString = self.htmlContent;
                    if(myHTMLString != nil) {
                        if([myHTMLString isEqualToString:@"3"]){
                            UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:@"LogIn Success" message:@"" delegate:self cancelButtonTitle:@"Continue" otherButtonTitles:nil];
                            self.view.userInteractionEnabled = YES;
                            [alrt show];


                        }
                        else{
                            UIAlertView *alrt = [[UIAlertView alloc] initWithTitle:@"LogIn Failed. Try again." message:@"User not authenticated" delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                            self.view.userInteractionEnabled = YES;
                            [alrt show];
                        }
                    }

                });

            }
        }
        else {
            dispatch_async(dispatch_get_main_queue(), ^{
                [self.spinner stopAnimating];
                [numEntered setText:@"0"];
                text = @"";
                UIAlertView *alrt = [[UIAlertView alloc]   initWithTitle:@"Requested file does not exist." message:@"Try again." delegate:self cancelButtonTitle:@"Ok" otherButtonTitles:nil];
                self.view.userInteractionEnabled = YES;
                [alrt show];
            });
        }
    }];
    [task resume];



}

Upvotes: 0

Views: 3575

Answers (2)

Qazi
Qazi

Reputation: 381

Since I can not comment I am writing as an Answer.

You need to check the error object to see the type of error that occured.

so in your else block you need to check error.localizedDescription to see what has happened, it would usually tell you that the file was not found or if the request timed out. you can even use your alert to show it like changing your else block as follows

else {
        dispatch_async(dispatch_get_main_queue(), ^{
            [self.spinner stopAnimating];
            [numEntered setText:@"0"];
            text = @"";
            UIAlertView *alrt = [[UIAlertView alloc] initWithTitle : @"Error"                                                                  
                                                           message : error.localizedDescription 
                                                          delegate : self 
                                                 cancelButtonTitle : @"Ok" 
                                                 otherButtonTitles : nil];
            self.view.userInteractionEnabled = YES;
            [alrt show];
        });
    }

Upvotes: 2

Vizllx
Vizllx

Reputation: 9246

You must use this delegate method to handle timeout:-

-(void) connection:(NSURLConnection * ) connection didFailWithError:(NSError *)error {    
    if (error.code == NSURLErrorTimedOut) 
        // handle error as you want 
        NSLog(@"Request time out");
}

Upvotes: 2

Related Questions