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

Asked

Viewed 690 times

1

I’m making a call POST with Swift using the Alamofire library. The service call works, but I need to check the email and the password user-typed.

How do I pass the variables email and senha in the parameters of the JSON?
Thanks in advance. Follow the part of my code that I am in need of help:

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;

    }
}

2 answers

0

You can user the syntax "if Let" as you did more up, together with "as?" :

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

Another way is to use "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)")
}
  • Thank you very much :)

0


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

if Let JSON = Response.result.value { print("JSON: (JSON)")

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

}

This way he identifies the parameters "id" and "name" and searches their values. Thank you, Fernando.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.