Wednesday, May 1, 2013

NSMutableURLRequest setTimeoutInterval example ios


Sets the receiver’s timeout interval, in seconds.
- (void)setTimeoutInterval:(NSTimeInterval)timeoutInterval
Parameters of [NSMutableURLRequest setTimeoutInterval]
The timeout interval, in seconds. If during a connection attempt the request remains idle for longer than the timeout interval, the request is considered to have timed out. The default timeout interval is 60 seconds.

Example of [NSMutableURLRequest setTimeoutInterval]
According to a post on the Apple developer forum, the minimum timeout interval for POST is 240 seconds. Any timeout interval shorter than that is ignored.

 NSURL *url = [NSURL URLWithString:urlString];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];    

    [request setTimeoutInterval:240];

    //Set the request method to post
    [request setHTTPMethod:@"POST"];

    if (body != nil) {
        [request setHTTPBody:body];

    // Add general parameters to the request
    if (authorization){
        [request addValue: authorization forHTTPHeaderField:@"Authorization"];
    [request addValue: WS_HOST forHTTPHeaderField:@"Host"];
    [request addValue:@"text/xml" forHTTPHeaderField:@"Content-Type"];

    [[NSURLCache sharedURLCache] setDiskCapacity:0];

    [self addToQueueRequest:request withDelegate:delegate];

Example of [NSMutableURLRequest setTimeoutInterval]
// call this when program first starts
-(void) nSendMessage : (NSString *) name  Password: (NSString *) password page: (NSString *) page

    // set the url
    NSString *address = @"http://localhost:1075/update";
    address=[ address stringByAppendingString: page];

    NSMutableURLRequest *request = 
    [[NSMutableURLRequest alloc] initWithURL: [NSURL URLWithString:address]];

    // post or get
    [request setHTTPMethod:@"POST"];

    // data to send
    NSString *postString = @"username=iusername&password=ipassword";
    NSString *sendString=[postString stringByReplacingOccurrencesOfString:@"iusername" withString: name];
    sendString=[sendString stringByReplacingOccurrencesOfString:@"ipassword" withString: password];

    [request setValue:[NSString 
                       stringWithFormat:@"%d", [sendString length]] 

    [request setHTTPBody:[sendString 

    [request setTimeoutInterval:240];
    [[NSURLConnection alloc] 
     initWithRequest:request delegate:self];