gpt4 book ai didi

ios - Swift 2 中的 Rest json POST 错误处理

转载 作者:行者123 更新时间:2023-11-30 14:02:39 24 4
gpt4 key购买 nike

Swift 2 的新手,我尝试在 Swift 2 中编写一个发出 HTTP POST 请求的应用程序,但我不知道如何使用 Swift 2.am 的新错误处理,使用 do try catch 方法,但仍然错误显示“由于未捕获的异常‘NSInvalidArgumentException’而终止应用程序,原因:‘*** +[NSJSONSerialization dataWithJSONObject:options:error:]:JSON 写入中的顶级类型无效”

这是在 swift 1.2 中运行的代码

//Post request to json
var request = NSMutableURLRequest(URL: NSURL(string: url)!)
var session = NSURLSession.sharedSession()
request.HTTPMethod = "POST"

var jsonString = "{\"Authentication\":{\"Username\":\"test\",\"Password\":\"test\"},\"RequestType\":4}"
var err: NSError?
request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in
//println("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) {
println(err!.localizedDescription)
let jsonStr = NSString(data: data!, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: '\(jsonStr)'")
//postCompleted(succeeded: false, msg: "Error")
}
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

let success = parseJSON["StatusCode"]as? Int

if(success == 200) {

println("success")
}
return
}
else {
// // Woa, okay the json object was nil, something went worng. Maybe the server isn't running?
let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
println("Error could not parse JSON: \(jsonStr)")
self.loadingIndicator.stopAnimating()
}
}
})
task.resume()

我正在 swift 2 中尝试以下代码

     //Post request to json
let request = NSMutableURLRequest(URL: NSURL(string: url)!)
let session = NSURLSession.sharedSession()
let jsonString : NSString = "{\"Authentication\":{\"Username\":\"\(usernameTextField.text)\",\"Password\":\"\(passwordTextField.text)\"},\"RequestType\":7}"
request.HTTPMethod = "POST"

//request.HTTPBody = jsonString.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: true)
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")


do {
let param = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(param!, options: [])
} catch {
print(error)
request.HTTPBody = nil
}


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()

最佳答案

let param = jsonString.dataUsingEncoding(NSUTF8StringEncoding)
request.HTTPBody = try NSJSONSerialization.dataWithJSONObject(param!, options: [])

在这里,您将字符串转换为 NSData,然后将结果提供给 dataWithJSONObject。真诚地,我怀疑这就是你想做的:)

试试这个:

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

关于ios - Swift 2 中的 Rest json POST 错误处理,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32794601/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com