我有在 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/