【发布时间】:2018-07-16 16:04:30
【问题描述】:
我的项目中有这段代码(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)",我得到了这个:
使用未解析的标识符“令牌”
我想我无法从另一个函数访问变量。
如何从另一个函数访问我的函数httpRequest() 中的该变量?
【问题讨论】:
-
没有名为
token的“一个变量”。每次调用application(_:didRegisterForRemoteNotificationsWithDeviceToken:)都会有一个token。多个线程可以一次调用该函数,并且每次调用都有自己的一组局部变量。因此,您不能访问另一个函数中的变量。您需要使用参数和返回值来传递数据。 -
另外,您不应该手动创建查询字符串。相反,请使用
NSURLQueryItemsgrokswift.com/building-urls