Hussein AlBehary Hussein AlBehary - 1 year ago 59
JSON Question

Can't get specified value from JSON in Swift 3

a quick explanation for what I'm doing, there is a login screen user types an email, then there is a verification viewController pops up, the backend sends a verification code to the user's email, if the user's email + the verification code matches then he is logged in successfully and the backend respond with user's full info + unique ID. So I want to get that unique ID alone.

My Verification viewController code:

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

}


But I only get the full response, I want the to get the Unique ID --> "BD_Id" alone so I can store it to use it in my app.

Here is the response:

{ 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 protected]","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":""}])


The ID did't print out, so what is my mistake ?

Thanks in advance. And please note that i'm very beginner in Swift Networking and thats my first time to deal with JSON.

UPDATE 1:

I have tried the following code but still didn't work, and the print statement didn't come out, that means that the data is empty||nil, but if that so how the last print statement prints the whole JSON script !

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)")
}

Answer Source

Try this ... your JSON is Array of Dictionaries .. [[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)")
  }
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download