1

I have this code in my project (Xcode 9.4.1 (9F2000), Swift 3):

func application(_ application: UIApplication,
                didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let tokenParts = deviceToken.map { data -> String in
        return String(format: "%02.2hhx", data)
    }
    let token = tokenParts.joined()
    print("Device Token: \(token)\n")
}
func httpRequest() {
    let postString = "token=\(token)"
}

This will print the device token for push notification.

But for let postString = "token=\(token)" I'm getting this:

Use of unresolved identifier 'token'

I guess I'm not able to access a variable from another function.

What can I do to access that variable in my function httpRequest() from the other function?

2
  • There isn't "one variable" called token. There is one token per invocation of application(_:didRegisterForRemoteNotificationsWithDeviceToken:). Multiple threads could call that function at once, and each invocation would have its own set of local variables. Thus, you can't access variables within another function. You need to use parameters and return values to pass data around. Commented Jul 16, 2018 at 16:09
  • Also, you shouldn't manually create query strings. Instead, use NSURLQueryItems grokswift.com/building-urls Commented Jul 16, 2018 at 16:11

1 Answer 1

3

You need to create a var for that

var myToken:String?

//

  func application(_ application: UIApplication,
                didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    let tokenParts = deviceToken.map { data -> String in
        return String(format: "%02.2hhx", data)
    }
    let token = tokenParts.joined()
    self.myToken = token
    print("Device Token: \(token)\n")
}
func httpRequest() {
    if let postString = myToken {
    }
}

Note : don't initiate any request until you receive the token , so either trigger a notification inside didRegisterForRemoteNotificationsWithDeviceToken to other parts of the app or run it end of the function after you get the token , also it's better storing the token or share it with a singleton for easy of access anywhere

Sign up to request clarification or add additional context in comments.

1 Comment

@Sh_KhanCan you please help me on this: stackoverflow.com/questions/51359471/…

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.