我是新手,这是我的第一个问题......我尝试在Swift 2中编写一个应用程序,发出HTTP POST请求,但我不知道如何使用Swift 2的新错误处理。有人能告诉我如何在下面的代码片段中实现Swift 2的“do-try-catch”错误处理吗?(此代码片段使用了Swift 1.2的旧错误处理)
func post(params : Dictionary<String, String>, url : String) {
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"
var err: NSError?
request.HTTPBody = NSJSONSerialization.dataWithJSONObject(params, options: nil/*, error: &err*/)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
print("Response: \(response)")
var strData = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Body: \(strData)")
var err: NSError?
var json = NSJSONSerialization.JSONObjectWithData(data!, options: .MutableLeaves/*, error: &err*/) as? NSDictionary
// Did the JSONObjectWithData constructor return an error? If so, log the error to the console
if(err != nil) {
print(err!.localizedDescription)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("Error could not parse JSON: '\(jsonStr)'")
}
else {
// 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
var 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()
}
2条答案
按热度按时间xxb16uws1#
您可能希望将
NSJSONSerialization
调用 Package 在do
/try
/catch
逻辑中,如下所示。在斯威夫特3中:
或者在《雨燕2》中
我还建议对
data
的强制解包要更小心一些,因为你想检测/处理错误,而不是崩溃。sshcrbum2#
一般来说,如果函数
throws
,您必须将其写入do catch
块中,或者仅将外部作用域函数(在本例中为post
)标记为throws
:如果你不想在你的
post
函数中处理这些错误,你可以直接声明它为throws
,而你根本不需要使用do catch