0

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

我尝试减少 [theRequest setTimeoutInterval: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
    }
4

1 回答 1

1

它冻结了你的应用程序,因为你已经告诉它了。您已将 YES 传递给 startImmediately。这意味着它将在该线程上启动连接并等待它完成。我猜您正在执行此操作的线程将是主线程 - 也处理 ui 等的线程 :)

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

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

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


编辑

像这样的东西:

self.web = [NSURLConnection connectionWithRequest:request delegate:self];
于 2011-12-01T11:51:04.523 回答