How to pass variables as a parameter on a JSON object in Swift?

1

I am making a POST call with Swift using the Alamofire library. The service call works, but I need to verify the email and the password typed by the user.

How do I pass variables email and senha into parameters of JSON? Thank you very much in advance. Here's the part of my code that I'm in need of help with:

let URL = NSURL(string: "http://jsonplaceholder.typicode.com/posts")!
let mutableURLRequest = NSMutableURLRequest(URL: URL)
mutableURLRequest.HTTPMethod = "POST"

let parameters = ["title": "Frist Psot", "body": "I iz fisrt", "userId": 1]

do {
    mutableURLRequest.HTTPBody = try NSJSONSerialization.dataWithJSONObject(parameters, options: NSJSONWritingOptions())
} catch{

}

mutableURLRequest.setValue("application/json", forHTTPHeaderField: "Content-Type")

Alamofire.request(mutableURLRequest)
    .responseJSON { response in
        print(response.response) // URL response
print(response.result)

if let JSON = response.result.value {
    print("JSON: \(JSON)")

    let usuario = JSON.objectForKey("data");
    print(usuario)
    //String nome = JSON.objectForKey("nome") == nil ? "" :JSON.objectForKey("nome") as! String;

    }
}
    
asked by anonymous 21.10.2015 / 22:07

2 answers

0

Thank you very much for the help. I was able to access my json object like this:

if let JSON = response.result.value {     print ("JSON: (JSON)")

let idUsuario = dataJSON["id"]
let nomeUsuario = dataJSON["nome"]
print(usuario)

}

In this way it identifies the parameters "id" and "name" and searches its values. Thank you so much, Fernando.

    
29.10.2015 / 20:03
0

You can user the "if let" syntax as you did above, in conjunction with "as?" :

  if let nome = jsonResult.objectForKey("nome") as? String {
            print(nome)
        }

Another way is to use the "as?" and check later:

var nome = jsonResult.objectForKey("nome") as? String
var senha = jsonResult.objectForKey("senha") as? String

if(nome != nil && senha != nil){
   print("\(nome) - \(senha)")
}
    
22.10.2015 / 20:12