gpt4 book ai didi

json - 在 Swift 中发布用户输入 JSON

转载 作者:行者123 更新时间:2023-11-30 12:04:54 25 4
gpt4 key购买 nike

我正在尝试从用户收集数据并将其发送到 Web 服务,但是我收到错误“JSON 写入中的顶级类型无效”我正在另一个函数中从 healthstore 收集步骤,并且所有数据都是在打印出来时正确地传递到 userhealthprofile 变量中。但是我的 JSON 代码有问题

完整的错误消息是

2017-10-17 09:30:57.170950+0200 IphoneReader[347:40755] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** +[NSJSONSerialization dataWithJSONObject:options:error:]: Invalid top-level type in JSON write'
*** First throw call stack:
(0x1d0b3b3d 0x1c33b067 0x1d0b3a85 0x1da763c1 0x9aa50 0x9bb60 0x2231a3b5 0x2231a349 0x22304979 0x22321f87 0x2286bf1b 0x22868833 0x22868423 0x22867849 0x223146f5 0x222e62bb 0x22a797f7 0x22a7419b 0x22a7457d 0x1d06ffdd 0x1d06fb05 0x1d06df51 0x1cfc11af 0x1cfc0fd1 0x1e76bb41 0x22349a53 0xa4d18 0x1c7ae4eb)
libc++abi.dylib: terminating with uncaught exception of type NSException

代码

@IBAction func submitAction(sender: AnyObject) {

userHealthProfile.name = nameLabel.text
print(userHealthProfile.name)

userHealthProfile.age = Int(ageLabel.text!)
print(userHealthProfile.age)

userHealthProfile.heightInMeters = Int(heightLabel.text!)
print(userHealthProfile.heightInMeters)

userHealthProfile.weightInKilograms = Int(weightLabel.text!)
print(userHealthProfile.weightInKilograms)

for element in stepy.step {
print(element)
}

userHealthProfile.totalStepsCount = stepy.step

print("pressing button")

//create the url with URL
let url = URL(string: "www.thisismylink.com/postName.php")!
//change the url

//create the session object
let session = URLSession.shared

//now create the URLRequest object using the url object
var request = URLRequest(url: url)
request.httpMethod = "POST" //set http method as POST

do {
request.httpBody = try JSONSerialization.data(withJSONObject: userHealthProfile, options: .prettyPrinted) // pass dictionary to nsdata object and set it as request body
} catch let error {
print(error.localizedDescription)
}

request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")

//create dataTask using the session object to send data to the server
let task = session.dataTask(with: request as URLRequest, completionHandler: { data, response, error in

guard error == nil else {
return
}
guard let data = data else {
return
}
do {
//create json object from data
if let json = try JSONSerialization.jsonObject(with: data, options: .mutableContainers) as? [String: Any] {
print(json)
// handle json...
}
} catch let error {
print(error.localizedDescription)
}
})
task.resume()
}

这就是用户配置文件的样子,这就是我需要作为 Web 服务的 jsonobject 发送的内容。

class UserHealthProfile {

var name: String?
var age: Int?
var totalStepsCount: Array<Any>!
var heightInMeters: Int?
var weightInKilograms: Int?

}

最佳答案

我认为你应该使用 Alamofire 来调用 Web API..这是根据您的要求提供的示例代码。

希望这对你有帮助......

func Submit(parametersToSend:NSDictionary)
{


Alamofire.request(.POST, "http://www.thisismylink.com/postName.php",parameters: parametersToSend as? [String : AnyObject], encoding: .URL).responseJSON
{
response in switch response.2
{
case .Success(let JSON):
print(JSON)
let response = JSON as! NSDictionary
print("My Web Api Response: \(response)")
break
case .Failure(let error):
print("Request failed with error: \(error)")
break
}

}

}

像这样在 @IBAction func SubmitAction(sender: AnyObject) 中调用函数

@IBAction func submitAction(sender: AnyObject) {

let steps = stepy.step
let name = nameLabel.text!
let age = Int(ageLabel.text!)
let height = Int(heightLabel.text!)
let weight = Int(weightLabel.text!)
let parameters = [
"name": name
"age": age
"totalStepsCount": steps
"heightInMeters": height
"weightInKilograms": weight
]
self.submit(parametersToSend:parameters)

}

关于json - 在 Swift 中发布用户输入 JSON,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46786231/

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