【问题标题】:Application freezes when sending a post request to the server向服务器发送发布请求时应用程序冻结
【发布时间】:2013-07-20 18:36:48
【问题描述】:
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);

上面的代码是在点击按钮时运行的,它将查询一个网络服务。

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

【问题讨论】:

    标签: ios objective-c foundation


    【解决方案1】:

    因为您使用的是 sendSynchronousRequest。

    请改用 sendAsynchronousRequest。

    【讨论】:

    【解决方案2】:

    您正在 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

    【讨论】:

      【解决方案3】:

      NSURLConnection 是苹果提供的更推荐的 URL 请求方式。下面我用request的委托方法名称简要解释了一个代码。它也可以防止阻塞应用程序的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

      【讨论】:

        猜你喜欢
        • 2019-12-02
        • 1970-01-01
        • 2016-02-27
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多