1

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)

}
Egle Matutyte
  • 225
  • 1
  • 8
  • 18

2 Answers2

1

As I mention in comment that you want to access your token everywhere in app you can do it this way:

Create a separate class for that like

import UIKit

class UserSettings: NSObject {

    class func setAuthToken(authToken: String?) {

        let defaults = NSUserDefaults.standardUserDefaults()
        defaults.setObject(authToken, forKey: "authToken");
    }

    class func getAuthToken() -> String? {
        let defaults = NSUserDefaults.standardUserDefaults()
        return defaults.stringForKey("authToken")
    }
}

Now you can set token this way:

let token = item["ubus_rpc_session"].stringValue
UserSettings.setAuthToken(token)

and you get token anywhere in app this way:

if let token = UserSettings.getAuthToken() {
    //do your stuff here with token
}
Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
1

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 https://stackoverflow.com/a/41899777/5886755

Community
  • 1
  • 1
  • 1
    Thank you, I tried the way with Userdefaults and it's working, but also I need second way, so I am going to use it later. – Egle Matutyte Feb 06 '17 at 07:28