Search code examples
iosjsonswift4

Unable to Extract token from JSON Response using Almofire in swift4


Can some one help me to how to extract token from one of my web services request using almofire in swift4. I want to store token in one of the variable. below I have posted the JSON response from my web service. Also I have posted the Code I have written in swift4. I am newbie to Swift4 so please let me know if you need additional information to answer my question. I have highlighted the code line in bold and commented where I am getting error. May be I am not reading JSON data correctly. I am newbie to JSON arrays and objects. Please help me with code sample.

JSON Response:

Successfully got data { data = { token = "eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJVc2VySWQiOiJiODcwY2Q4My0zZDMzLTQ1ODgtYmZlMi00MzQ0ODQ4ZmJiOGMiLCJDb250YWN0SWQiOiJiODU4NTAyYy1lZGM2LTRlY2QtYTk0ZC1kMjEwNmI3YjZlMmQiLCJuYmYiOjE1Njk4Mjk1OTAsImV4cCI6MTU2OTgzNjc5MCwiaWF0IjoxNTY5ODI5NTkwfQ.LO2Z4n0IRYaaJM6Pmp8pLeo3alDPmioaAF4ces2K-9M"; }; message = ""; status = Success; }

I can able to extract the status from above JSON Response but I am not able to extract the token Below is my swift4 code.

import UIKit
import Alamofire
import SwiftyJSON

class ViewController: UIViewController{
let URL_USER_LOGIN = "some url"
  let defaultValues = UserDefaults.standard

@IBOutlet weak var labelMessage: UILabel!
    @IBOutlet weak var textFieldUserName: UITextField!

    @IBOutlet weak var textFieldPassword: UITextField!

    @IBAction func buttonLogin(_ sender: Any) {

let parameters: Parameters=[
            "username":textFieldUserName.text!,
            "password":textFieldPassword.text!
        ]


Alamofire.request(URL_USER_LOGIN, method: .post,parameters: parameters,encoding: JSONEncoding.default, headers: headers).responseJSON
            {

                response in
let jsonData = response.result.value as? NSDictionary
let status = jsonData? ["status"] as! String

// when I use **tokendata = jsonData? ["token"] as! String**   I am getting Error Please help me with code fixes 

if status == "Success" {

let profileViewController = self.storyboard?.instantiateViewController(withIdentifier: "ProfileViewcontroller") as! ProfileViewController
                        self.navigationController?.pushViewController(profileViewController, animated: true)


                        self.dismiss(animated: false, completion: nil)

                    }else{
                        //error message in case of invalid credential
                        let alert = UIAlertController(title: "Alert", message: "Email or Passowrd is Not matching", preferredStyle: .alert)
                        let ok = UIAlertAction(title: "Ok", style:.default, handler: nil)
                        alert.addAction(ok)
                        self.present(alert, animated: true, completion: nil)
                        //self.labelMessage.text = "Invalid username or password"
                    }
                }
        }


 override func viewDidLoad() {
        super.viewDidLoad()

        let backButton = UIBarButtonItem(title: " ", style: UIBarButtonItem.Style.plain, target: navigationController, action: nil)
        navigationItem.leftBarButtonItem = backButton

        if defaultValues.string(forKey: "username") != nil{
            let profileViewController = self.storyboard?.instantiateViewController(withIdentifier: "ProfileViewcontroller") as! ProfileViewController
            self.navigationController?.pushViewController(profileViewController, animated: true)

        }
    }

override func viewWillAppear(_ animated: Bool) {
        navigationController?.isNavigationBarHidden = true
    }

Solution

  • First, you have to modify your JSON response. because it is not well formated. your JSON should be like following.

    {
      "status" : "Success",
      "message" : "your message",
      "data":{"token" : "your_token"}
    }
    

    You are using SwiftyJSON. so you can parse your value with SwiftyJSON like following

    let json = try JSON(data: response.data)
    
    let status = json["status"].stringValue
    
    let message = json["message"].stringValue 
    
    let data = json["data"].dictionaryValue
    
    let token = data["token"]?.stringValue