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?

David
  • 2,898
  • 3
  • 21
  • 57
  • 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. – Alexander Jul 16 '18 at 16:09
  • Also, you shouldn't manually create query strings. Instead, use `NSURLQueryItems` https://grokswift.com/building-urls/ – Alexander Jul 16 '18 at 16:11

1 Answers1

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

Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87
  • @Sh_KhanCan you please help me on this: https://stackoverflow.com/questions/51359471/uiprogressview-is-not-updating-inside-uicollectionview-in-swift3-ios – user2786 Jul 16 '18 at 16:13