Reputation: 3348
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?
Upvotes: 1
Views: 3172
Reputation: 100541
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
Upvotes: 3