Question

NSString *post = [NSString stringWithFormat:@"email=%@",_benimEmail]; 
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES]; 
NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; 
[request setURL:[NSURLURLWithString:@"http://localhost:8888/iphone/msg.php"]]; 
[request setHTTPMethod:@"POST"]; 
[request setValue:postLength forHTTPHeaderField:@"Content-Length"]; 
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"]; 
[request setHTTPBody:postData];

NSError *error; NSURLResponse *response; 
NSData *urlData = [NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error]; 
NSString *veri = [[NSString alloc]initWithData:urlData encoding:NSUTF8StringEncoding]; 
NSLog(@"%@",veri);

This code above is run on a button click, and it will query a web service.

Now, when I click on the button, the application freezes for a while. How can I prevent this from happening?

Was it helpful?

Solution

its because you are using sendSynchronousRequest.

Use sendAsynchronousRequest instead.

OTHER TIPS

You are performing blocking calls on UI thread and that is causing the freeze.

You could use ASIHTTPRequest (not maintained but works fine) class and use their method to do async network call

- (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];
}

or you can look into the more superior AFNetworking library

NSURLConnection is provided by apple is more recommended way of placing URL request. Below I explained a code in brief with the name of delegate methods of request.It will also prevent to block the UI of app.

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:url]];
[[NSURLConnection alloc] initWithRequest:request delegate:self];

and handle its response and errors using its delegate methods.

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
- (void)connectionDidFinishLoading:(NSURLConnection *)connection 

You can find implementation of NSURLConnection

NSURLConnectionDocs

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top