Swift - downcast NSURLResponse to NSHTTPURLResponse in order to get response code

后端 未结 1 1048
时光说笑
时光说笑 2020-12-06 11:28

I\'m building rest queries in SWIFT using NSURLRequest

var request : NSURLRequest = NSURLRequest(URL: url)

var connection : NSURLConnection = NSURLConnecti         


        
相关标签:
1条回答
  • 2020-12-06 11:55

    Use an optional cast (as?) with optional binding (if let):

    func connection(didReceiveResponse: NSURLConnection!, didReceiveResponse response: NSURLResponse!) {
        if let httpResponse = response as? NSHTTPURLResponse {
            println(httpResponse.statusCode)
        } else {
            assertionFailure("unexpected response")
        }
    }
    

    or as a one-liner

    let statusCode = (response as? NSHTTPURLResponse)?.statusCode ?? -1
    

    where the status code would be set to -1 if the response is not an HTTP response (which should not happen for an HTTP request).

    0 讨论(0)
提交回复
热议问题