2
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 服务。

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

4

3 回答 3

2

这是因为您使用的是 sendSynchronousRequest。

请改用 sendAsynchronousRequest。

于 2013-07-20T18:38:55.627 回答
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

于 2014-07-02T08:55:38.730 回答
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

于 2013-07-20T18:41:41.650 回答