Swift 2中的HTTP POST错误处理

Swift 2中的HTTP POST错误处理,http,post,error-handling,nsjsonserialization,swift2,Http,Post,Error Handling,Nsjsonserialization,Swift2,我是新来的,这是我的第一个问题。。。 我尝试在Swift 2中编写一个发出HTTP POST请求的应用程序,但我不知道如何使用Swift 2的新错误处理。有人能告诉我如何在下面的代码片段中实现Swift 2的“do try catch”错误处理吗? (此代码段使用swift 1.2的旧错误处理) func post(参数:字典,url:String){ var request=NSMutableURLRequest(URL:NSURL(字符串:URL)!) var session=NSURLSe

我是新来的,这是我的第一个问题。。。 我尝试在Swift 2中编写一个发出HTTP POST请求的应用程序,但我不知道如何使用Swift 2的新错误处理。有人能告诉我如何在下面的代码片段中实现Swift 2的“do try catch”错误处理吗? (此代码段使用swift 1.2的旧错误处理)

func post(参数:字典,url:String){
var request=NSMutableURLRequest(URL:NSURL(字符串:URL)!)
var session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
变量错误:n错误?
request.HTTPBody=NSJSONSerialization.dataWithJSONObject(参数,选项:nil/*,错误:&err*/)
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
var task=session.dataTaskWithRequest(请求,completionHandler:{data,response,error->Void in
打印(“响应:\(响应)”)
var strData=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“正文:\(标准数据)”)
变量错误:n错误?
var json=NSJSONSerialization.JSONObjectWithData(data!,选项:.MutableLeaves/*,错误:&err*/)为?NSDictionary
//JSONObjectWithData构造函数是否返回错误?如果是,请将错误记录到控制台
如果(错误!=nil){
打印(错误!.localizedDescription)
让jsonStr=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“错误无法分析JSON:'\(jsonStr)'”)
}
否则{
//JSONObjectWithData构造函数没有返回错误。但是,我们仍然应该
//使用可选绑定检查并确保json具有值。
如果让parseJSON=json{
//好的,parsedJSON在这里,让我们从中获得“成功”的价值
var success=parseJSON[“success”]as?Int
打印(“成功:\(成功)”)
}
否则{
//哇,好吧,json对象为零,出现了问题。可能服务器没有运行?
让jsonStr=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“错误无法解析JSON:\(jsonStr)”)
}
}
})
任务!.resume()
}

通常,如果函数
抛出
,则必须将其写入
do catch
块中,或仅将外部作用域函数(在本例中为
post
)标记为
抛出

func post(params : Dictionary<String, String>, url : String) {
    let request = NSMutableURLRequest(URL: NSURL(string: url)!)
    let session = NSURLSession.sharedSession()
    request.HTTPMethod = "POST"

    do {
        request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: .PrettyPrinted)
    } catch {
        //handle error. Probably return or mark function as throws
        print(error)
        return
    }
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")

    let task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
        // handle error
        guard error == nil else { return }

        print("Response: \(response)")
        let strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
        print("Body: \(strData)")

        let json: NSDictionary?
        do {
            json = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves) as? NSDictionary
        } catch let dataError {
            // Did the JSONObjectWithData constructor return an error? If so, log the error to the console
            print(dataError)
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: '\(jsonStr)'")
            // return or throw?
            return
        }


        // The JSONObjectWithData constructor didn't return an error. But, we should still
        // check and make sure that json has a value using optional binding.
        if let parseJSON = json {
            // Okay, the parsedJSON is here, let's get the value for 'success' out of it
            let success = parseJSON["success"] as? Int
            print("Succes: \(success)")
        }
        else {
            // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
            let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
            print("Error could not parse JSON: \(jsonStr)")
        }

    })

    task!.resume()
}
func post(参数:字典,url:String){
let request=NSMutableURLRequest(URL:NSURL(string:URL)!)
let session=NSURLSession.sharedSession()
request.HTTPMethod=“POST”
做{
request.HTTPBody=尝试NSJSONSerialization.dataWithJSONObject(参数,选项:。预打印)
}抓住{
//处理错误。可能将函数返回或标记为抛出
打印(错误)
返回
}
request.addValue(“应用程序/json”,forHTTPHeaderField:“内容类型”)
request.addValue(“application/json”,forHTTPHeaderField:“Accept”)
让task=session.dataTaskWithRequest(请求,completionHandler:{data,response,error->Void in
//处理错误
保护错误==nil else{return}
打印(“响应:\(响应)”)
让strData=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“正文:\(标准数据)”)
让json:NSDictionary?
做{
json=尝试NSJSONSerialization.JSONObjectWithData(data!,选项:.MutableLeaves)作为NSDictionary
}捕获let数据错误{
//JSONObjectWithData构造函数是否返回错误?如果是,请将错误记录到控制台
打印(数据错误)
让jsonStr=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“错误无法分析JSON:'\(jsonStr)'”)
//回击还是投掷?
返回
}
//JSONObjectWithData构造函数没有返回错误。但是,我们仍然应该
//使用可选绑定检查并确保json具有值。
如果让parseJSON=json{
//好的,parsedJSON在这里,让我们从中获得“成功”的价值
让success=parseJSON[“success”]作为?Int
打印(“成功:\(成功)”)
}
否则{
//哇,好吧,json对象为零,出现了问题。可能服务器没有运行?
让jsonStr=NSString(数据:data!,编码:NSUTF8StringEncoding)
打印(“错误无法解析JSON:\(jsonStr)”)
}
})
任务!.resume()
}

如果您不想在
post
函数中正确处理这些错误,您可以将其声明为
throws
,而不必使用
do catch
,您可能想将
NSJSONSerialization
调用封装在
do
/
try
/
/
逻辑中,如下所示

在Swift 3中:

var request = URLRequest(url: URL(string: urlString)!)

let session = URLSession.shared
request.httpMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.httpBody = try! JSONSerialization.data(withJSONObject: parameters)

// or if you think the conversion might actually fail (which is unlikely if you built `parameters` yourself)
//
// do {
//    request.httpBody = try JSONSerialization.data(withJSONObject: parameters)
// } catch {
//    print(error)
// }

let task = session.dataTask(with: request) { data, response, error in
    guard let data = data, error == nil else {
        print("error: \(error)")
        return
    }

    // this, on the other hand, can quite easily fail if there's a server error, so you definitely
    // want to wrap this in `do`-`try`-`catch`:

    do {
        if let json = try JSONSerialization.jsonObject(with: data) as? [String: Any] {
            let success = json["success"] as? Int                                  // Okay, the `json` is here, let's get the value for 'success' out of it
            print("Success: \(success)")
        } else {
            let jsonStr = String(data: data, encoding: .utf8)    // No error thrown, but not dictionary
            print("Error could not parse JSON: \(jsonStr)")
        }
    } catch let parseError {
        print(parseError)                                                          // Log the error thrown by `JSONObjectWithData`
        let jsonStr = String(data: data, encoding: .utf8)
        print("Error could not parse JSON: '\(jsonStr)'")
    }
}

task.resume()
或者,用Swift 2

let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)

let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])

// or if you think the conversion might actually fail (which is unlikely if you built `parameters` yourself)
//
// do {
//    request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])
// } catch {
//    print(error)
// }

let task = session.dataTaskWithRequest(request) { data, response, error in
    guard let data = data where error == nil else {
        print("error: \(error)")
        return
    }

    // this, on the other hand, can quite easily fail if there's a server error, so you definitely
    // want to wrap this in `do`-`try`-`catch`:

    do {
        if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
            let success = json["success"] as? Int                                  // Okay, the `json` is here, let's get the value for 'success' out of it
            print("Success: \(success)")
        } else {
            let jsonStr = String(data: data, encoding: NSUTF8StringEncoding)    // No error thrown, but not NSDictionary
            print("Error could not parse JSON: \(jsonStr)")
        }
    } catch let parseError {
        print(parseError)                                                          // Log the error thrown by `JSONObjectWithData`
        let jsonStr = String(data: data, encoding: NSUTF8StringEncoding)
        print("Error could not parse JSON: '\(jsonStr)'")
    }
}

task.resume()
我还建议您在强制展开
数据时要更加小心,因为您希望检测/处理错误,而不是崩溃。例如,上面我使用
guard
语句将其展开

let request = NSMutableURLRequest(URL: NSURL(string: urlString)!)

let session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

request.HTTPBody = try! NSJSONSerialization.dataWithJSONObject(parameters, options: [])

// or if you think the conversion might actually fail (which is unlikely if you built `parameters` yourself)
//
// do {
//    request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(params, options: [])
// } catch {
//    print(error)
// }

let task = session.dataTaskWithRequest(request) { data, response, error in
    guard let data = data where error == nil else {
        print("error: \(error)")
        return
    }

    // this, on the other hand, can quite easily fail if there's a server error, so you definitely
    // want to wrap this in `do`-`try`-`catch`:

    do {
        if let json = try NSJSONSerialization.JSONObjectWithData(data, options: []) as? NSDictionary {
            let success = json["success"] as? Int                                  // Okay, the `json` is here, let's get the value for 'success' out of it
            print("Success: \(success)")
        } else {
            let jsonStr = String(data: data, encoding: NSUTF8StringEncoding)    // No error thrown, but not NSDictionary
            print("Error could not parse JSON: \(jsonStr)")
        }
    } catch let parseError {
        print(parseError)                                                          // Log the error thrown by `JSONObjectWithData`
        let jsonStr = String(data: data, encoding: NSUTF8StringEncoding)
        print("Error could not parse JSON: '\(jsonStr)'")
    }
}

task.resume()