为什么我的应用程序冻结时,我用NSURLRequest的POST请求



我有一个这样的方法。当我的设备通过wifi网络连接时,它可以正常工作,但当它通过3G网络连接时,它会冻结我的应用程序几秒钟。因为它是一个交互式应用,当它做一些post请求时它必须继续运行,这样用户才能继续使用这个应用。有什么解决办法吗?

我尝试减少[therequestsettimeoutinterval:2.0];但这并没有解决我的问题。

// post request
    - (void)postRequestWithURL:(NSString *)url 
                                body:(NSString *)body 
                         contentType:(NSString *)contentType 
                             options:(NSDictionary *)dict
    {
        // set request
        NSURL *requestURL = [NSURL URLWithString:url];
        NSMutableURLRequest *theRequest = [[NSMutableURLRequest alloc] init];

        if([dict count] > 0)
        {
            for (id key in dict) {
                NSLog(@"[theRequest addValue:%@ forHTTPHeaderField:%@]", [dict valueForKey:key], key);
                [theRequest addValue:[dict valueForKey:key] forHTTPHeaderField:key];
            }
        }
        if (contentType != nil) {
            [theRequest addValue:contentType forHTTPHeaderField:@"Content-type"];
        }
        [theRequest setURL:requestURL];
        [theRequest setTimeoutInterval:2.0];
        [theRequest setHTTPMethod:@"POST"];
        [theRequest setHTTPBody:[body dataUsingEncoding:NSASCIIStringEncoding]];
        [self.oauthAuthentication authorizeRequest:theRequest];
        // make request
        //responseData = [NSURLConnection sendSynchronousRequest:theRequest 
        //                                   returningResponse:&response 
        //                                               error:&error]; 
        NSURLConnection *conn = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
        self.web = conn;
        [conn release];
        NSLog(@"########## REQUEST URL: %@", url);


        // request and response sending and returning objects
    }

它正在冻结你的应用程序,因为你已经让它冻结了。您已将YES传递到startimimmediate。这意味着它将在该线程上启动连接,并等待连接完成。我猜你正在做这件事的线程将是主线程-也处理ui等的线程:)

你需要使用像connectionWithRequest:delegate:这样的东西-这将在后台运行请求并告诉你何时完成。

PS你没有发现wifi漏洞的原因是因为数据发送得太快了,你无法注意到应用程序中的暂停:)

PPS超时没有修复的原因是因为请求没有超时-它只是获取数据非常慢:)


编辑

像这样:

self.web = [NSURLConnection connectionWithRequest:request delegate:self];

相关内容

最新更新