【问题标题】:Swift: Get variable in function from another functionSwift:从另一个函数获取函数中的变量
【发布时间】: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。多个线程可以一次调用该函数,并且每次调用都有自己的一组局部变量。因此,您不能访问另一个函数中的变量。您需要使用参数和返回值来传递数据。
  • 另外,您不应该手动创建查询字符串。相反,请使用 NSURLQueryItems grokswift.com/building-urls

标签: ios swift xcode swift3


【解决方案1】:

您需要为此创建一个 var

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 内向应用程序的其他部分触发通知,要么在获得令牌后在函数结束时运行它token ,最好存储 token 或与单例共享,以便在任何地方轻松访问

【讨论】:

猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-06-30
  • 2011-01-18
  • 1970-01-01
  • 2014-01-22
  • 1970-01-01
  • 2012-08-02
  • 1970-01-01
相关资源
最近更新 更多