NSURLConnection在发出请求后没有响应

时间:2014-10-01 10:30:02

标签: ios web-services nsurlconnection

我编写了以下代码来从Web服务获取数据:

- (void)fetchOnlineUserList
{
    NSString *strURL=[NSString stringWithFormat:@"%s%s",ServerPath,URLUserList];
    NSMutableURLRequest *updateRequest = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:strURL]
                                                                 cachePolicy:NSURLRequestUseProtocolCachePolicy
                                                             timeoutInterval:60.0];
    [updateRequest setHTTPMethod:@"POST"];
    NSString *postString = [NSString stringWithFormat:@"userid=%@",[[NSUserDefaults standardUserDefaults] objectForKey:@"user_id"]];
    [updateRequest setHTTPBody:[postString dataUsingEncoding:NSUTF8StringEncoding]];
    [updateRequest setValue:@"" forHTTPHeaderField:@"Accept-Encoding"];
    NSURLConnection * connection = [[NSURLConnection alloc]
                                    initWithRequest:updateRequest
                                    delegate:self startImmediately:NO];

    [connection scheduleInRunLoop:[NSRunLoop mainRunLoop]
                          forMode:NSDefaultRunLoopMode];
    [connection start];
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    webData = [NSMutableData data];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    [webData appendData:data];
}

- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    //Process data
}

- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    //Connection failed
}

但问题是,大多数时候这种方法效果很好,有时则不然。从某种意义上讲,它不起作用,它不会触发任何委托方法,甚至连接失败也不会触发。但有时它完美无缺。这可能是什么问题?我的应用程序中有很多Web请求,而且大多数时候只有少数Web服务显示这个奇怪的错误。而且大部分它都可以在模拟器中完美运行。在上面的代码中,我在主线程中运行连接。我正在使用[NSURLConnection connectionWithRequest:updateRequest delegate:self]发出请求,但后来我遇到了这个问题,stackoverflow中的许多答案告诉我在主线程中运行连接,所以我改变了我的代码。

0 个答案:

没有答案