在iOS中检索HTTPResponse/HTTPRequest状态代码?

cmc*_*loh 28 objective-c nsurlconnection ios

我需要检查并评估我的iPhone应用程序中的HTTP状态代码.我有一个NSURLRequest对象和一个成功(我认为)连接到该站点的NSURLConnection:

// create the request
NSURLRequest *theRequest=[NSURLRequest requestWithURL:[NSURL URLWithString:@"http://www.apple.com/"]
                        cachePolicy:NSURLRequestUseProtocolCachePolicy
                    timeoutInterval:60.0];
// create the connection with the request
// and start loading the data
NSURLConnection *theConnection=[[NSURLConnection alloc] initWithRequest:theRequest delegate:self];
if (theConnection) {
    // Create the NSMutableData that will hold
    // the received data
    // receivedData is declared as a method instance elsewhere
    receivedData=[[NSMutableData data] retain];
} else {
    // inform the user that the download could not be made
}
Run Code Online (Sandbox Code Playgroud)

我在这里得到了这个代码:https://web.archive.org/web/20100908130503/http : //developer.apple.com/iphone/library/documentation/Cocoa/Conceptual/URLLoadingSystem/Tasks/UsingNSURLConnection.html

但它(据我所知)并没有说出访问HTTP状态代码的任何信息.

如何建立与站点的连接,然后检查该连接的HTTP状态代码?

Rob*_*Rob 76

我是这样做的:

    #pragma mark -
    #pragma mark NSURLConnection Delegate Methods
    - (void)connection:(NSURLConnection*)connection didReceiveResponse:(NSURLResponse*)response {
         NSHTTPURLResponse* httpResponse = (NSHTTPURLResponse*)response;
         int responseStatusCode = [httpResponse statusCode];
    }
Run Code Online (Sandbox Code Playgroud)

但我正在使用异步NSURLConnection,所以这可能对你没有帮助.但我希望它能做到!

  • 看看Apple的Reachabilty代码.仅使用通知方法(默认情况下未在代码中启用,请参阅init方法中的注释)并始终设置要检查的主机.http://stackoverflow.com/questions/477852/checking-for-internet-connectivity-in-objective-c (3认同)