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