Warning: file_get_contents(/data/phpspider/zhask/data//catemap/6/ant/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
使用HTTPURLResponse代替URLResponse_Http_Swift3 - Fatal编程技术网

使用HTTPURLResponse代替URLResponse

使用HTTPURLResponse代替URLResponse,http,swift3,Http,Swift3,我想调用一个API,它是我应用程序的一部分,但我想确保我得到了我要调用的站点的状态代码(以防止运行时错误)。我无法获取URLResponse的状态代码,但我可以获取HTTPURLResponse的状态代码。如何使用后者代替前者 let requestURLString = "my_http_url" let requestURL = URL(string: requestURLString) let config = URLSessionConfiguration.def

我想调用一个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)

        }

    }

但是,
urresponse
httpurresponse
被重命名为loss
NS
-前缀。它们仍然是类,
httpurresponse
urresponse
的子类

您可以使用
as?
as

    if
        error == nil,
        let httpResponse = response as? HTTPURLResponse
    {
        switch httpResponse.statusCode {
        case 200:
            //...
            break
        //...
        default:
            break
        }
    } else {
        //error case here...
    }