EieN
EieN

Reputation: 11

variable value is null.Why?

I'm new to swift i have my problem. no variables are assigned. test variable why null? No problem writing code in loop.you help.thanks

print(test.count) = 0 why?

sorry beginner english

var test = ""

ApiClient.shared.login(username:"acilrezervasyon" , password: "acilrezervasyon", successBlock:  { (response, value) in
    let accessToken = value!.accessToken
    Utils.setToken(accessToken!)

    //print(accessToken)

    ApiClient.shared.allProvidersCars(alisKonum: "28", alisTarihi: "2017-11-22", alisSaati: "10:00", teslimKonum: "28", testlimTarihi: "2017-11-23", teslimTarihi: "2017-11-23", teslimSaati: "10:00", successBlock:  { (response, value) in
        let araclarDatasi = value!.data
        // print(araclarDatasi)

        if let results: NSArray = araclarDatasi as? NSArray {
            results.forEach { veri in
                let araclarModeli = AllProvidersCar(JSON: veri as! [String : Any])

                araclarModeli?.araclar.forEach { arac in
                    let arac = JSON(arac)
                    print(arac["ARACADI"])

                    test = "emre" /**/
                }
            }
        }
    })
})

print(test.count)

Upvotes: 1

Views: 121

Answers (1)

Ozgur Vatansever
Ozgur Vatansever

Reputation: 52203

ApiClient.shared does not make the caller wait while retrieving data from network. It works asynchronously so it passes the fetched data to its success block when the network operation is done.

Thus, at the time allProvidersCars method is called, your program will already have reached the line where you print test so it'll be printed out before you do test = "emre".

For this specific example, the easiest way to keep the execution waiting is to use a DispatchSemaphore. You create a semaphore, call .wait() on the semaphore right after .allProvidersCars() starts working so that the code will wait till you release the semaphore. And you'll release it after test has been set.

Here is a quick demonstration showing how you'd do it in your code:

(Note: You should never freeze the main thread, so I'll do this in the background queue.)

var test = ""

let queue = DispatchQueue.global(qos: .background)
queue.async {
  let semaphore = DispatchSemaphore(value: 1)

  ApiClient.shared.login(..., successBlock: { .. in  
    ApiClient.shared.allProvidersCars(..., successBlock:  { .. in
      ...
      if let results: NSArray = araclarDatasi as? NSArray {
        ...
        test = "emre"
      }
      semaphore.signal()
    }
  }
  semaphore.wait()
  print(test)
}

Upvotes: 2

Related Questions