使用HTTPURLResponse代替URLResponse

Ron*_*Aja 3 http swift3

我想调用API及其应用程序的一部分,但我想确保获得要调用的站点的状态代码(以防止运行时错误)。我无法获取URLResponse的状态代码,但可以获取HTTPURLResponse的状态代码。如何使用后者代替前者?

    let requestURLString = "my_http_url"
    let requestURL = URL(string: requestURLString)
    let config = URLSessionConfiguration.default
    let session = URLSession(configuration: config)
    let ETAreq = session.dataTask(with: requestURL!)
    {

        (data, response (this is the URLResponse), error) in

        if error == nil
        {

            //switch (this is where I will put switch of status code)

        }

    }
Run Code Online (Sandbox Code Playgroud)

OOP*_*Per 5

虽然,URLResponse并且HTTPURLResponseNS-prefix 命名。它们仍然是类,HTTPURLResponse是的子类URLResponse

HTTPURLResponse

您可以使用as?as!

    if
        error == nil,
        let httpResponse = response as? HTTPURLResponse
    {
        switch httpResponse.statusCode {
        case 200:
            //...
            break
        //...
        default:
            break
        }
    } else {
        //error case here...
    }
Run Code Online (Sandbox Code Playgroud)