Handle HTTP error with NSURLSession?

前端 未结 5 1306
挽巷
挽巷 2021-01-07 16:33

I\'m trying to send a HTTP request with NSURLSession. It works fine, but when the server doesn\'t respond I can\'t find where the HTTP error code is stored. The

5条回答
  •  盖世英雄少女心
    2021-01-07 16:58

    Swift 3:

    // handle basic connectivity issues here
    guard error == nil else {
        print("Error: ", error!)
        return
    }
    
    // handle HTTP errors here
    if let httpResponse = response as? HTTPURLResponse {
        let statusCode = httpResponse.statusCode
    
        if (statusCode != 200) {
            print ("dataTaskWithRequest HTTP status code:", statusCode)
            return;
        } 
    }
    
    if let data = data {
        // here, everything is probably fine and you should interpret the `data` contents
    }
    

提交回复
热议问题