Swift: 从另一个函数获取函数中的变量
Swift: Get variable in function from another function
我的项目中有这段代码(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)"
}
这将打印推送通知的设备令牌。
但是对于 let postString = "token=\(token)"
我得到这个:
Use of unresolved identifier 'token'
我想我无法从另一个函数访问变量。
如何从另一个函数访问我的函数 httpRequest()
中的那个变量?
您需要为此创建一个变量
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 {
}
}
注意: 在收到令牌之前不要发起任何请求,因此要么在 didRegisterForRemoteNotificationsWithDeviceToken
内触发通知到应用程序的其他部分,要么 运行 它在您获得令牌后结束函数,而且最好存储令牌或与单例共享它以便于在任何地方访问
我的项目中有这段代码(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)"
}
这将打印推送通知的设备令牌。
但是对于 let postString = "token=\(token)"
我得到这个:
Use of unresolved identifier 'token'
我想我无法从另一个函数访问变量。
如何从另一个函数访问我的函数 httpRequest()
中的那个变量?
您需要为此创建一个变量
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 {
}
}
注意: 在收到令牌之前不要发起任何请求,因此要么在 didRegisterForRemoteNotificationsWithDeviceToken
内触发通知到应用程序的其他部分,要么 运行 它在您获得令牌后结束函数,而且最好存储令牌或与单例共享它以便于在任何地方访问