Problems with prepareDesign method

Asked

Viewed 77 times

0

I have 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 this variable to a viewcontroller by next, however the variable when I pass the method prepareForSee it picks the variable as null or when I started it:

To explain better

1 - I installed a variable at the beginning of my view class "A"

var id = ""

2 - I made the Nsurlsession and took the json of a Rest per post and put inside the Dispatch to store in the variable that I installed.

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 dentor it instanciei the Destination and put the value of the instantiated variable in view A for the variable 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
        }
    }

THAT LINE: viewA.idb = self.id

when you’re in this way prepareForSee it won’t that I’m picking it up in JSON it goes "" like when I instantiate.

Someone can help me?

Thank you!

2 answers

0

The following must be happening before the request comes back. Try calling performSegueWithIdentifier within the request block, after the self.id = idretorno.

0

In the stretch below:

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!
  })
}

Try assigning the id variable before Dispatch, and check with Debug that the variable is being filled in.

Browser other questions tagged

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