Stacy J Stacy J - 2 months ago 15
JSON Question

How to convert login data in json format in swift

I am new to iOS development. I have created a view which accepts the users phone number and password.

The api that lets a user logs in takes the login data in json format :-

{
"login_details":[
{
"mobile":"**************",
"password":"XXXXXXXXX"
}
]
}


I am able to get the textfield data and print it

let mobile = phoneTextField.text;
let password = passwordTextField.text;


How do I now convert this to required json format?

Answer

You can store your input data in a Dictionary and pass it with the name label like that

    let userData = ["mobile":"432423432424","password":"123"]

    let dict:NSMutableDictionary = NSMutableDictionary()
    dict.setValue(userData, forKey: "login_details")

    let jsonData = try! NSJSONSerialization.dataWithJSONObject(dict, options: NSJSONWritingOptions.allZeros)
    let jsonString = NSString(data: jsonData, encoding: NSUTF8StringEncoding) as! String

     print(jsonString)