ios - appdelegate swift4 中的全局变量

标签 ios swift

我有在 appDelegate 中创建的变量。我如何在 ViewController 中使用这个变量。我尝试了几种方法,但是。我总是出错。我的代码如下。我是新来的,请帮忙?

AppDelegate.swift

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {

// refreshedToken is variable. I use it in viewcontroller.
        if let refreshedToken = InstanceID.instanceID().token() {
            print("InstanceID token: \(refreshedToken)")

       }
}

ViewController.swift

   super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.

    let appDelegate = UIApplication.shared.delegate as! AppDelegate


    let purl = URL(string: "")!
    var request = URLRequest(url: purl)
    request.setValue("application/x-www-form-urlencoded", forHTTPHeaderField: "Content-Type")
    request.httpMethod = "GET"
    let postString = "ajax=token&"+"token="+refreshedToken// Use of unresolved identifier 'refreshedToken'

    print("postString: \(postString)")
    request.httpBody = postString.data(using: .utf8)
    request.addValue("application/json", forHTTPHeaderField: "Content-Type")
    request.addValue("application/json", forHTTPHeaderField: "Accept")
    let task = URLSession.shared.dataTask(with: request) { data, response, error in
        guard let data = data, error == nil else {
            print("error=\(String(describing: error))")
            return
        }

        if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 {
            print("statusCode should be 200, but is \(httpStatus.statusCode)")
            print("response = \(String(describing: response))")
        }

        let responseString = String(data: data, encoding: .utf8)
        print("responseString = \(String(describing: responseString))")
    }
    task.resume()






}

如何在 ViewController 中使用 refreshedToken?

最佳答案

您需要了解您在什么范围内声明一个变量,以及它在该范围外是如何可见的。现在您的变量仅在该函数内可见,要使其对您的 View Controller 可见,它需要成为 AppDelegate 中的类属性。

所以定义一个属性(这里稍微简化了代码)

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {
   var refreshedToken = InstanceID.instanceID().token()
   ...

}

然后你可以在你的 View Controller 中访问它

let token = appDelegate.refreshedToken

关于ios - appdelegate swift4 中的全局变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49954785/

相关文章:

ios - 使用 Xcode 在 iOS 应用程序中调用网页

iphone - 添加没有 PKAddPassesViewController 实例的通行证

swift - 看起来返回键对我的方法不起作用

html - 通过根据 html 标签调整单元格大小,使用 UITextView 在 UITableViewCell 中显示 html [不是 UILabel!]

swift - swift 3 中的 Unix 时间戳转换问题

ios - IBM Worklight 6.0 - "Instrumentation Failed"错误

objective-c - iOS - 向 CakePHP REST 发出 POST 请求

ios - 如何将响应数据设置到 TodayExtension 小部件中

ios - 在 spritekit swift 中触摸节点时不播放声音

ios - Objective-C 项目中的 Swift CocoaPods 库