Stacy J Stacy J - 1 year ago 93
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 :-


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 Source

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download