gpt4 book ai didi

ios - 无法从 Swift 3 中的 JSON 获取指定值

转载 作者:行者123 更新时间:2023-11-28 21:13:47 26 4
gpt4 key购买 nike

快速解释一下我在做什么,有一个登录屏幕,用户输入一封电子邮件,然后弹出一个验证 viewController,后端向用户的电子邮件发送验证码,如果用户的电子邮件 + 验证代码匹配然后他成功登录并且后端响应用户的完整信息+唯一ID。 所以我想单独获取那个唯一 ID。

我的验证 View Controller 代码:

@IBAction func doneBtnPressed(_ sender: Any) {

let request = NSMutableURLRequest(url: NSURL(string: "http://anydomain.com/verif.php")! as URL)
request.httpMethod = "POST"
let postString = "bdemail=\(bdEmail)&verifcode=\(verifyCodeTxtField.text!)"
request.httpBody = postString.data(using: String.Encoding.utf8)

let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in

if error != nil {
print("error=\(error)")
return
}else {
do {
if let data = data,
let json = try JSONSerialization.jsonObject(with: data) as? [String: Any],
let users = json["BD_Id"] as? [[String: Any]] {
print(users)
}
} catch {
print("Error deserializing JSON: \(error)")
}
}

print("response = \(response)")

let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString)")
}

task.resume()

self.performSegue(withIdentifier: "mySegueIdentifier", sender: nil)

}

但我只得到完整的响应,我想单独获得唯一 ID --> “BD_Id”,这样我就可以存储它以在我的应用中使用它。

回复如下:

    { URL: http://anydomain.com/verif.php } { status code: 200, headers {
Connection = "Keep-Alive";
"Content-Type" = "text/html; charset=UTF-8";
Date = "Tue, 07 Feb 2017 07:40:00 GMT";
Server = Apache;
"Transfer-Encoding" = Identity;
} })


responseString = Optional( [{"Rcode":101,"BD_Id":"8","BD_Name":"","BD_Email":"email@domain.com","BD_Country":"","BD_Home_Lat":"","BD_Home_Lon":"","BD_BT":"","BD_RH":"","BD_DOB":"0000-00-00","BD_Mobile":"","BD_Last_Donation":"0000-00-00","BD_Token":""}])

ID 没有打印出来,所以我的错误是什么?

提前致谢。请注意,我是 Swift Networking 的初学者,那是我第一次处理 JSON。

更新 1:

我试过下面的代码还是不行,print语句也没有出来,说明数据是空的||nil,但是如果是这样最后的print语句怎么打印出整个JSON脚本!

let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in

if error != nil {
print("error=\(error)")
return
}else {
do {
if data != nil {
print("Hello from the inside...")
let json = try JSONSerialization.jsonObject(with: data!) as? [[String: Any]]
for obj in json! {
if let bdId = obj["BD_Id"] as? String {
print(bdId)
}
}
}
} catch {
print("Error deserializing JSON: \(error)")
}
}

print("response = \(response)")

let responseString = NSString(data: data!, encoding: String.Encoding.utf8.rawValue)
print("responseString = \(responseString)")
}

最佳答案

试试这个……你的 JSON 是字典数组 .. [[String:Any]]

  do{
let json = try JSONSerialization.jsonObject(with: data!, options:[]) as! [[String:Any]]
for obj in json {
if let bdId = obj["BD_Id"] as? String {
print(bdId)
}
}
}
catch {
print("Error with Json: \(error)")
}

关于ios - 无法从 Swift 3 中的 JSON 获取指定值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42084370/

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