I'm having a problem guys, I'm new to swift, and I have a method that takes a result from a JSON and I wanted to store it in a local variable and then pass that variable to a viewcontroller next, but the variable when step in the prepareForStack method it picks up the variable as null or when I started it:
To explain better
1 - I instantiated a variable at the beginning of my view class "A"
var id = ""
2 - I did the NSURLSession and got the json from one rest per post and put it inside the dispatch to store in the variable that I instantiated.
func postQueEstouFazendo(v1: NSString, v2: NSString, v3: NSString)
{
//url para aonde vou mandar o post
let myUrl = NSURL(string: "http://minhapiqueestoupegando");
//inicia a variavel que vai fazer o request
let request = NSMutableURLRequest(URL:myUrl!);
//define o metodo do request
request.HTTPMethod = "POST";// Compose a query string
//coloca os dados em uma string de dados com um titulo
let postString = "variavel=\(v1)&variavel2=\(v2)&variavel3=\(v3)";
//define o encoding do que vai ser passado
request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding);
//inicia o envio dos dados
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) {
data, response, error in
//se o erro de envio existir mostra um print
if error != nil
{
print("error ao fazer o recolhimento =\(error)")
return
}
//aqui é a resposta do envio
// You can print out response object
print("response = \(response)")
//aqui é uma outra forma mais completa de visualizar o retorno do envio
// Print out response body
let responseString = NSString(data: data!, encoding: NSUTF8StringEncoding)
print("responseString = \(responseString)")
//teste
//Let's convert response sent from a server side script to a NSDictionary object:
do
{
let myJSON = try NSJSONSerialization.JSONObjectWithData(data!, options: .MutableContainers) as? NSDictionary
if let parseJSON = myJSON
{
// Now we can access value of First Name by its key
let idretorno = parseJSON["retorno"] as? String
//faz a chamada da view voltando para a main thread!
dispatch_async(dispatch_get_main_queue(), {
self. id = idretorno!
})
}
}
catch
{
print(error)
}
}
task.resume() // fim do envio e volta pra thread principal ja que a task é uma background thread
}
3 - I made the method PrepareForSegue and its instantiated the destination and put the value of the instantiated variable in view A for the variable that I want to pass to view B
//Segues
override func shouldPerformSegueWithIdentifier(identifier: String, sender: AnyObject?) -> Bool {
return true
}
override func prepareForSegue(segue: UIStoryboardSegue, sender: AnyObject?){
if segue.identifier == "meuidentifier"
{
var viewA: viewB = segue.destinationViewController as! viewB
viewA.idb = self.id
viewA.outravariavel= 0
}
}
THIS LINE: viewA.idb = self.id
When it is in this method prepareForSegue it will not what I'm getting it in the JSON it will "" like when I instantiate it.
Can anyone help me?
Thank you!