Egle Matutyte Egle Matutyte - 4 years ago 102
Swift Question

Alamofire using value outside completion handler

I made a request to server with Alamofire and get data from it with completion handler, but I want to use some value outside of it, is it possible to do that?

let retur = Json().login(userName: param1, password: param2) { (json) in

print(json)

let jsonDic = JSON(json)
for item in jsonDic["result"].arrayValue {
let token = item["ubus_rpc_session"].stringValue
}

print(jsonDic["result"][1]["ubus_rpc_session"].stringValue)

}

Answer Source

If you want to access result outside the Alamofire then follow below code.

        override func viewDidLoad()
         {
           super.viewDidLoad()

          let retur = Json().login(userName: param1, password: param2) { (json) in

            print(json)

            let jsonDic = JSON(json)
            for item in jsonDic["result"].arrayValue
            {
                    let token = item["ubus_rpc_session"].stringValue
                    self.myFunction(str: token)
            }

            print(jsonDic["result"][1]["ubus_rpc_session"].stringValue)

        }
      }

         func myFunction(str: String)
         {
            //Here it will print token value.
            print("Token value ====%@",str)
         }

Solution 2:

Here I'll use NSUserDefault, to know more about it you can search about it, there are multiple examples are available on google.

Now here, we will use NSUserDefault.

//Use below code in alamofire block to save token value.

    let defaults = UserDefaults.standard
    defaults.set(token, forKey: "tokenValue")

    //Use below code to print anywhere.

        let defaults = UserDefaults.standard
        if let myToken = defaults.value(forKey: "tokenValue") as? String
        {
            print("defaults savedToken: \(myToken)")
        }

Hope it works for you.

For more details you can refer this answer http://stackoverflow.com/a/41899777/5886755

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download