Search code examples
jsonswiftnsdictionarynsjsonserialization

How to add multiple paramaters[String,Dictionary] in a dictionary using swift?


I am building iOS Application using Swift.I am using XCODE version 6.3. I want to post data to server using JSON.For that i created a dictionary for performing the following operation.

//This is my dictionary right now
 var parameters = ["authenticity_token":name,"platform":"mobileApp", "email": userEmail, "password": userPassword,"remember_me":"1"]

 request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err)

I want to pass data as the format shown below.

{"authenticity_token":"token","platform":"mobileApp",
"user":{"email":"email_id", "password":"123456",
 "remember_me":"1"}}

Right now parameter dictionary in the Format

[platform: mobileApp, authenticity_token: a1oj3olt5jn169LHn59ZbfbrBVUyov7sDVHlOl+2YzE=, email: [email protected], remember_me: 1, password: samrat]

order of the paramater also changed. I want to pass to my dictionary. Or is there any possibility to add two dictionaries.

This is my code for posting data to server.I have another confusion whether it is correct or not.

 func postData()
  {
     let name = defaults.stringForKey("secretKey")

    var parameters = ["authenticity_token":name,"platform":"mobileApp", "email": userEmail, "password": userPassword,"remember_me":"1"]

    println("Dic\(parameters)")
    let url = NSURL(string: "http://behance.moblearn.net/users/sign_in")
    var session = NSURLSession.sharedSession()
    let request = NSMutableURLRequest(URL: url!)
    request.HTTPMethod = "POST"

    var err: NSError?
    request.HTTPBody = NSJSONSerialization.dataWithJSONObject(parameters, options: nil, error: &err)

     let jsonStr = NSString(data: request.HTTPBody!, encoding: NSUTF8StringEncoding)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    println("Post Method reached")

    var task = session.dataTaskWithRequest(request, completionHandler: {data, response, error -> Void in

    println("Response: \(response)")
    var strData = NSString(data: data, encoding: NSUTF8StringEncoding)
    println("Body: \(strData)")
    var err: NSError?
    var json = NSJSONSerialization.JSONObjectWithData(data, options: .MutableLeaves, error: &err) as? NSDictionary

      if(err != nil) {
        println(err!.localizedDescription)
        let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
        println("Error could not parse JSON: '\(jsonStr)'")
    }
    else {

        if let parseJSON = json {
            var success = parseJSON["success"] as? Int
            println("Succes: \(success)")
        }
        else {
            let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding)
            println("Error could not parse JSON: \(jsonStr)")
        }
    }
})
task.resume()
}

I am in deep trouble.I am Beginner in swift.Help will be appreciated.


Solution

  • Do like this:

    let innerDict = ["email": "email_id", "password": "123456", "remember_me": "1"]
    let mainDict = ["authenticity_token": "token", "platform": "mobileApp", "user": innerDict]