代码之家  ›  专栏  ›  技术社区  ›  Nnp

处理nsurlconnection sendSynchronousRequest时出错

  •  20
  • Nnp  · 技术社区  · 16 年前

    如何更好地处理nsurlconnection sendSynchronousRequest的错误?我有什么办法可以实现吗

    - (void)connection:(NSURLConnection *)aConn didFailWithError:(NSError *)error
    

    我有一个nsOperation队列,它在后台获取数据,这就是为什么我有同步请求。 如果必须实现异步请求,那么如何等待请求完成。因为没有数据这个方法就无法继续。

    2 回复  |  直到 14 年前
        1
  •  30
  •   Alex    14 年前

    -sendSynchronousRequest:returningResponse:error:为您提供了一种方法,使您能够在方法本身中立即获得错误。最后一个参数实际上是(nserrror**)错误;也就是说,指向nserrror指针的指针。试试这个:

    NSError        *error = nil;
    NSURLResponse  *response = nil;
    
    [NSURLConnection sendSynchronousRequest: req returningResponse: &response error: &error];
    
    if (error) {...handle the error}
    
        2
  •  55
  •   Community Mohan Dere    9 年前

    我不会依靠非零的错误来表示发生了错误。

    我一直在使用本答案中描述的错误检查,但我相信它在某些情况下会产生假阳性/假阳性错误。

    按照这个 SO answer ,我将更改为使用方法的结果来确定成功/失败。然后(并且只有在这时)检查错误指针以了解失败的详细信息。

    NSError *requestError;
    NSURLResponse *urlResponse = nil;
    NSData *response = [NSURLConnection sendSynchronousRequest:request returningResponse:&urlResponse error:&requestError];
    /* Return Value
       The downloaded data for the URL request. Returns nil if a connection could not be created or if the download fails.
    */
    if (response == nil) {
        // Check for problems
        if (requestError != nil) {
            ...
        }
    }
    else {
        // Data was received.. continue processing
    }
    

    这种方法可以避免对下载过程中发生的错误做出反应,而不会导致失败。我认为下载过程中可能会遇到框架内处理的非关键错误,它们会产生用错误对象设置错误指针的副作用。

    例如,我已经从下载了应用程序的用户那里得到了POSIX错误报告,这些应用程序似乎是在处理URL连接的过程中发生的。

    此代码用于报告错误:

    NSString *errorIdentifier = [NSString stringWithFormat:@"(%@)[%d]",requestError.domain,requestError.code];
    [FlurryAPI logError:errorIdentifier message:[requestError localizedDescription] exception:nil];
    

    错误报告为:

    Platform: iPhone
    Error ID: (NSPOSIXErrorDomain)[22]
    Msg: Operation could not be completed. Invalid argument
    

    把它映射回来……

    requestError.domain = NSPOSIXErrorDomain
    requestError.code = 22
    [requestError localizedDescription] = Operation could not be completed. Invalid argument
    

    我所能找到的就是错误代码22是 EINVAL 但这并没有产生任何进一步的细节。

    我得到的其他错误来自于nsurl域,在不同的网络条件下,我完全预料到这一点:

    NSURLErrorTimedOut
    NSURLErrorCannotConnectToHost
    NSURLErrorNetworkConnectionLost
    NSURLErrorNotConnectedToInternet
    +others