1

I have to file inside my project, 1 - view.swift and the 2 - login.swift. I have a function inside my login.swift which will get a token from a site that i provide. Then I need that token which my function gets from the site and i want to use it in my view.swift, But I cant't get it outside that func no matter what I do.

The code is like this :

 struct universal{
 static var token = String()
 static var passkey = String()
 }
 class LoginManager {

 let loginURL = "http://somesite.com"

 func login() {
    let parameters: Parameters = [
        "username": "username",
        "password": "password",
        "device": "gtv",
        "redir": "0"
    ]

    Alamofire.request(loginURL, method: .get, parameters: parameters).responseJSON { (response) in

        let jsonRes = JSON(data: response.data!)
        var token = jsonRes["token"].stringValue
        // the value of universal.token is not print outside of this func nither the token. But both of them can get the value here and when printing them it shows the value
        universal.token = jsonRes["token"].stringValue
   }



   }

Im newbie so don't be mean. I just try to learn.

The question is how can i get only value not just closure or use entire func in other class if possible

Armin
  • 33
  • 6
  • just save the token in the UserDefault – Gurinder Batth Jan 27 '17 at 16:29
  • I don't know how to do it and how to access it outside – Armin Jan 27 '17 at 16:30
  • Can we see the code you are using to access the data outside the Alamofire closure? What triggers the data access? – Mike Sand Jan 27 '17 at 16:31
  • 1
    Possible duplicate of [How to return value from Alamofire](http://stackoverflow.com/questions/27390656/how-to-return-value-from-alamofire) – milo526 Jan 27 '17 at 16:32
  • I use it in my "IF" to check if user got token nothing so fancy – Armin Jan 27 '17 at 16:32
  • @milo526 bro Im not sure you read what i asked. I read that post and he has what he need but i need to get all the value i want when each user logged in and keep them and in next view I will get lots of link from the JSON file in my host and provide lots of link for that user. – Armin Jan 27 '17 at 16:43

3 Answers3

0

Your current request is asynchronous, this means you will need to supply the function with a code block that can be executed after the request finished.

You can pass your token to this block and do whatever you want with it.

Take a look at this post for more information and some code as on how to implement this.

Community
  • 1
  • 1
milo526
  • 5,012
  • 5
  • 41
  • 60
  • He had his own customer key and etc. I need to get all of them when user logged in. this is my problem. I read that post – Armin Jan 27 '17 at 16:41
0

Edit: Using UserDefaults works for something like a token but you should know how to coordinate data coming from API calls, it's basis of so much iOS programming.

This code looks fine. Probably you are checking for the token before the asynchronous Alamofire call has returned.

class ViewControllerThatNeedsToken : UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        if Universal.token != "" {
            //There's a token already...
            self.doSomething(with: universal.token)
        } else {
            //Handle not having a token yet
        }
    }

    func doSomething(with token: String) {
         //do something 
    }
}

Then in your API call:

    let referenceToNeedsToken : ViewControllerThatNeedsToken = //...get reference 

    Alamofire.request(loginURL, method: .get, parameters: parameters).responseJSON { [weak referenceToNeedsToken] (response) in

        let jsonRes = JSON(data: response.data!)
        var token = jsonRes["token"].stringValue
        // the value of universal.token is not print outside of this func nither the token. But both of them can get the value here and when printing them it shows the value
        Universal.token = jsonRes["token"].stringValue
        referenceToNeedsToken?.doSomething(with: Universal.token)
   }

Note that when putting a reference, you need to put the [weak referenceToNeedsToken] in the closure. Then use optional chaining, referenceToNeedsToken?.doSomething(with: Universal.token) since if the view controller doesn't exist you probably don't want to do anything anymore.

Note also the struct name should be in capitalized because it it's a type. Hope this helps.

Mike Sand
  • 2,750
  • 14
  • 23
0

I think you want to access value outside the Alamofire block, and which you can't print outside the 'Alamofire' block right.

Solution: Below I've edited your coding stuff, try to implement it. Here I will show you, how you can access your token value outside Alamofire block, further you can implement it as per your requirement.

     struct universal
     {
         static var token = String()
         static var passkey = String() 
     }

     class LoginManager 
    {

     let loginURL = "http://somesite.com"

     func login()
     {
        let parameters: Parameters = [
            "username": "username",
            "password": "password",
            "device": "gtv",
            "redir": "0"
        ]

        Alamofire.request(loginURL, method: .get, parameters: parameters).responseJSON { (response) in

            let jsonRes = JSON(data: response.data!)
            var token = jsonRes["token"].stringValue

            self.myFunction(str: token)

            universal.token = jsonRes["token"].stringValue

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

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 helps you.