Thursday, September 13, 2012

Web service request in applicationDidEnterBackground

applicationDidEnterBackground: will always be called when the home button is pressed.I had an issue of indicating the server that "user is not using the app right now"  anytime whenever user presses home button.To do this i need to call web service request inside applicationDidEnterBackground: i used NSURLConnection inside it.
Look at the following method to get a clear pic on it


- (void)applicationDidEnterBackground:(UIApplication *)application
{
    
    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    
    [request setURL:[NSURL URLWithString:urlString];
    
    [request setHTTPMethod:@"POST"];
    
    [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"content-type"];
    
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:nil];
    
    NSString *json_string = [[NSString alloc] initWithData:response encoding:NSUTF8StringEncoding];
    
    NSDictionary *results = [json_string JSONValue];
    
    NSLog(@"BG task:%@",results);

}

response will have the result of the request handled.

Note:

sendSynchronousRequest:returningResponse:error:

Performs a synchronous load of the specified URL request.
A synchronous load is built on top of the asynchronous loading code made available by the class. The calling thread is blocked while the asynchronous loading system performs the URL load on a thread spawned specifically for this load request. No special threading or run loop configuration is necessary in the calling thread in order to perform a synchronous load.






1 comment: