How to check status of web server in iOS?

2019-09-05 17:32发布

问题:

I need to check status of web server, specifically, the information if the web server returns proper status code 200. Is there any way to get the HTTP response code from web server in iOS?

回答1:

This is well documented in the official docs, with no need to implement a 3rd party library (although if you're new to iOS coding, a Networking API can simplify the underlying function calls). Your class must be an NSURLConnection delegate, and after making the NSURLConnection you implement the delegate method something like this:

-(void)connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse*)response 
{
    if ([response statusCode] == 200) {
        // Handle valid response (You can probably just let the connection continue)
    }
    else {
        // Other status code logic here (perhaps cancel the NSURLConnection and show error)
    }
}

You should find the URL Loading Guide very useful reading for this and other networking functions on iOS.



标签: ios http