NSURLConnection有时会失败 - 服务器无法访问?

时间:2016-02-10 13:33:43

标签: objective-c nsurlconnection

如何检测NSURLConnection故障是否是由于服务器无法访问?

我检查了服务器的日志,当NSURLConnection失败时,在这些情况下没有提及应用程序的调用。但是,尝试启动NSURLConnection(见下文)是否因为其他原因而失败?

我通过一个包含以下init函数的包装器来实现对NSURLConnection的调用:

-(id)initWithURL:(NSURL*)url
        postData:(NSData*)postData
    responseData:(NSMutableData*)responseData
        delegate:(id)delegate
    doneSelector:(SEL)doneSelector
   errorSelector:(SEL)errorSelector {

    if(self=[super init]) {
        _url = [url retain];
        _postData = [postData retain];
        _responseData = [responseData retain];
        _delegate = [delegate retain];
        _doneSelector = doneSelector;
        _errorSelector = errorSelector;

        // Set up request
        NSMutableURLRequest* request = [[[NSMutableURLRequest alloc] init] autorelease];
        [request setURL:_url];
        [request setHTTPMethod:@"POST"];
        [request setValue:[NSString stringWithFormat:@"%d",[_postData length]] forHTTPHeaderField:@"Content-Length"];
        [request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
        [request setHTTPBody:_postData];

        // Kick off the connection
        NSURLConnection* connection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES];
        if(!connection) {
            [_delegate performSelector:_errorSelector];
        }
    }
    return self;
}

我们在测试期间从未遇到过这个问题(并且99%的时间URL连接对我们的用户来说完美无缺)所以我无法确定NSURLConnection的确切位置。我确实知道,当它失败时,errorSelector会被一个空的_responseData字符串调用。

您是否看到上述代码中的任何内容在极少数情况下可能会失败?

知道如何找到连接失败的原因吗?

提前致谢!

0 个答案:

没有答案