timeout of NSMutableURLRquest

Discussion in 'iOS Programming' started by Howiieque, Apr 19, 2010.

  1. Howiieque macrumors regular

    Joined:
    Feb 1, 2009
    #1
    hi all,
    Code:
    		NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
    		[urlRequest setHTTPMethod:@"POST"];
    		[urlRequest setTimeoutInterval:15.0];
    //		urlRequest.timeoutInterval=0.5;
    		NSString *body=[NSString stringWithFormat:@"username=%@&password=%@", account, password];
    		[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
    		NSURLConnection *urlConnection=[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self];
    no matter how i set the timeout, it won't work. but if i use sendSynchronousRequest: method, it works.
    could someone tell me why?
     
  2. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #2
    What do you mean by "it doesn't work"? You haven't set the delegate as far as I can see or implemented any callbacks. Where are you detecting this "not working". Please be as precise as possible.
     
  3. Howiieque thread starter macrumors regular

    Joined:
    Feb 1, 2009
    #3
    thank you for your reply and sorry for my uncertain question.
    i meant it won't timeout exactly as i specified.
    i implemented the delegate methods( the 4 most common ones), and everything works perfectly.
    except that if it can not reach the data, it would probably last about 3 mins before timeout. the problem is that i specified 15 seconds. and the default value is 60 seconds. i could not figure it out why almost 3 minutes' waiting.
    hope this time someone can give me some tips.
     
  4. robbieduncan Moderator emeritus

    robbieduncan

    Joined:
    Jul 24, 2002
    Location:
    London
    #4
    Post all the code including the delegate methods: it's possible that has something to do with it.
     
  5. Howiieque thread starter macrumors regular

    Joined:
    Feb 1, 2009
    #5
    Code:
    //
    //  GKLoginViewController.m
    //  GK
    //
    //  Created by Howiieque on 19/04/2010.
    //  Copyright 2010 __MyCompanyName__. All rights reserved.
    //
    
    #import "GKLoginViewController.h"
    
    #import <CFNetwork/CFNetwork.h>
    
    
    @implementation GKLoginViewController
    
    @synthesize delegate;
    @synthesize accountField;
    @synthesize passwordField;
    @synthesize loginButton;
    @synthesize indicator;
    
    /*
     // The designated initializer.  Override if you create the controller programmatically and want to perform customization that is not appropriate for viewDidLoad.
    - (id)initWithNibName:(NSString *)nibNameOrNil bundle:(NSBundle *)nibBundleOrNil {
        if (self = [super initWithNibName:nibNameOrNil bundle:nibBundleOrNil]) {
            // Custom initialization
        }
        return self;
    }
    */
    
    /*
    // Implement viewDidLoad to do additional setup after loading the view, typically from a nib.
    - (void)viewDidLoad {
        [super viewDidLoad];
    }
    */
    
    /*
    // Override to allow orientations other than the default portrait orientation.
    - (BOOL)shouldAutorotateToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation {
        // Return YES for supported orientations
        return (interfaceOrientation == UIInterfaceOrientationPortrait);
    }
    */
    
    - (IBAction)login {
    //	[delegate loginViewControllerDidFinish:self];
    	NSString *account=[accountField text];
    	NSString *password=[passwordField text];
    	if ([account isEqualToString:@"Howie"] && [password isEqualToString:@"Chan"]) {
    		[self storeLoginRecord];
    		[delegate loginViewControllerDidFinish:self];
    	} else if (account!=nil && password!=nil && ![account isEqualToString:@""] && ![password isEqualToString:@""]) {
    		loginButton.enabled=NO;
    		NSString *uniqueIdentifier=[UIDevice currentDevice].uniqueIdentifier;
    		NSURL *url=[NSURL URLWithString:@"some url..."];
    		NSMutableURLRequest *urlRequest=[NSMutableURLRequest requestWithURL:url];
    		[urlRequest setHTTPMethod:@"POST"];
    		[urlRequest setTimeoutInterval:15.0];
    //		urlRequest.timeoutInterval=0.5;
    		NSString *body=[NSString stringWithFormat:@"username=%@&password=%@&authcode=%@&mobile=0", account, password, uniqueIdentifier];
    		[urlRequest setHTTPBody:[body dataUsingEncoding:NSUTF8StringEncoding]];
    		NSURLConnection *urlConnection=[[NSURLConnection alloc] initWithRequest:urlRequest delegate:self startImmediately:YES];
    		NSAssert(urlConnection!=nil, @"Failure to create Login URL connection.");
    		[UIApplication sharedApplication].networkActivityIndicatorVisible=YES;
    		[indicator startAnimating];
    	} else {
    		UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Account & Password must not be Empty", @"Displayed when account/password is/are empty") message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    		[alertView show];
    		[alertView release];
    	}
    }
    
    #pragma mark -
    #pragma mark NSURLConnection delegate methods
    
    - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
    	rawData=[[NSMutableData alloc] initWithCapacity:0];
    }
    
    
    - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    	[rawData appendData:data];
    }
    
    
    - (void)connectionDidFinishLoading:(NSURLConnection *)connection {
    	[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
    	[indicator stopAnimating];
    	[connection release];
    	[self didFinishDownloadingData];
    }
    
    
    - (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
    	[UIApplication sharedApplication].networkActivityIndicatorVisible=NO;
    	[indicator stopAnimating];
    	[connection release];
    	[rawData release];
    	if ([error code]==kCFURLErrorNotConnectedToInternet) {
    		NSDictionary *userInfo=[NSDictionary dictionaryWithObject:NSLocalizedString(@"No Connection Error", @"Error message displayed when not connected to the Internet.") forKey:NSLocalizedDescriptionKey];
    		NSError *noConnectionError=[NSError errorWithDomain:NSCocoaErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:userInfo];
    		[self handleError:noConnectionError];
    	} else {
    		[self handleError:error];
    	}
    }
    
    #pragma mark -
    
    - (void)didFinishDownloadingData {
    	NSString *response=[[NSString alloc] initWithData:rawData encoding:NSUTF8StringEncoding];
    	[rawData release];
    	NSArray *array=nil;
    	@try {
    		array=[response propertyList];
    		if ([(NSString *)[array objectAtIndex:0] isEqualToString:@"1"]) {
    			[delegate loginViewControllerDidFinish:self];
    		} else {
    			UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:(NSString *)[array objectAtIndex:1] message:nil delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    			[alertView show];
    			[alertView release];
    			loginButton.enabled=YES;
    		}
    	}
    	@catch (NSException * e) {
    		NSLog(@"Wrong XML format.");
    		NSDictionary *userInfo=[NSDictionary dictionaryWithObject:NSLocalizedString(@"Server Error", @"Error message displayed when encounters wrong xml format.") forKey:NSLocalizedDescriptionKey];
    		NSError *xmlError=[NSError errorWithDomain:NSCocoaErrorDomain code:kCFURLErrorNotConnectedToInternet userInfo:userInfo];
    		[self handleError:xmlError];
    	}
    	@finally {
    		[response release];
    	}
    }
    
    
    - (void)handleError:(NSError *)error {
    	NSString *errorMessage=[error localizedDescription];
    	UIAlertView *alertView=[[UIAlertView alloc] initWithTitle:NSLocalizedString(@"Login Error", @"Title for alert displayed when download or parse error occurs.") message:errorMessage delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
    	[alertView show];
    	[alertView release];
    	loginButton.enabled=YES;
    }
    
    #pragma mark -
    
    - (void)storeLoginRecord {
    	NSString *uniqueIdentifier=[UIDevice currentDevice].uniqueIdentifier;
    	NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    	NSString *documentsDirectory=[paths objectAtIndex:0];
    	NSString *filePath=[documentsDirectory stringByAppendingPathComponent:@"permission.plist"];
    	[uniqueIdentifier writeToFile:filePath atomically:YES encoding:NSUTF8StringEncoding error:NULL];
    }
    
    #pragma mark -
    
    - (void)didReceiveMemoryWarning {
    	// Releases the view if it doesn't have a superview.
        [super didReceiveMemoryWarning];
    	
    	// Release any cached data, images, etc that aren't in use.
    }
    
    - (void)viewDidUnload {
    	// Release any retained subviews of the main view.
    	// e.g. self.myOutlet = nil;
    	self.accountField=nil;
    	self.passwordField=nil;
    	self.loginButton=nil;
    	self.indicator=nil;
    }
    
    
    - (void)dealloc {
    	[accountField release];
    	[passwordField release];
    	[loginButton release];
    	[indicator release];
        [super dealloc];
    }
    
    
    @end
    
    i can provide a little bit more if needed. thank you.
     

Share This Page