将发布请求发送到服务器时,应用程序冻结

时间:2013-07-20 18:36:48

标签: ios objective-c foundation

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);

上面的代码在点击按钮上运行,它将查询Web服务。

现在,当我点击按钮时,应用程序会冻结一段时间。我怎样才能防止这种情况发生?

3 个答案:

答案 0 :(得分:2)

因为你正在使用sendSynchronousRequest。

改为使用sendAsynchronousRequest。

答案 1 :(得分:0)

您正在对UI线程执行阻止调用,这会导致冻结。

您可以使用ASIHTTPRequest(未维护但工作正常)类并使用其方法执行异步网络调用

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

或者您可以查看更高级的AFNetworking

答案 2 :(得分:0)

NSURLConnection是苹果提供更推荐的放置URL请求的方式。下面我简要介绍了代码委托方法名称的代码。它还可以防止阻止应用程序的UI。

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

并使用其委托方法处理其响应和错误。

- (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 

您可以找到NSURLConnection的实现

NSURLConnectionDocs