2016-09-16 10 views
0

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

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) 

     } 

    } 

回答

0

虽然,和HTTPURLResponse被重命名为失去NS - 前缀。他们仍然是类,HTTPURLResponse是的子类。

HTTPURLResponse

您可以使用as?as!

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

非常感谢它的实际工作! –