Ios appdelegate swift4中的全局变量

Ios appdelegate swift4中的全局变量,ios,swift,Ios,Swift,我有在appDelegate中创建的变量。如何在ViewController中使用此变量。我试过几种方法,但是。我总是出错。我的代码如下。我是新来的请帮忙 AppDelegate.swift func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) { // refreshedToken is variable. I use

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

只需在appdelegate类中全局创建refreshedToken,并按如下方式更新代码:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var refreshedToken : String?

    func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
        // refreshedToken is variable. I use it in viewcontroller.
        if let token = InstanceID.instanceID().token() {
            self.refreshedToken = token
            print("InstanceID token: \(refreshedToken)")

        }
    }
}
从上面的代码中,如果调用了DeviceToken方法,则refreshedToken可用,否则它将为零

若您希望它在应用程序中全局可用,而不依赖于任何方法,请在AppDelegate类实现之后编写以下代码

let refreshedToken = InstanceID.instanceID().token()

您需要了解在什么范围内声明变量,以及变量在该范围外是如何可见的。现在,您的变量仅在该func中可见,要使其对视图控制器可见,它需要是AppDelegate中的类属性

所以定义一个属性,比如(这里的代码稍微简化)

然后在中,您可以在视图控制器中访问它

let token = appDelegate.refreshedToken

您可以将刷新令牌保存在UserDefaults中

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)")
            UserDefaults.standard.set(refreshedToken, forKey: "preferenceName")

       }
}
及更高版本可以使用

let postString = "ajax=token&"+"token="+  UserDefaults.standard.string(forKey: "Key")

您可以使用Singleton模型对象来处理这个问题,该对象将保存您的数据,并且可以从项目的任何地方全局访问数据

首先创建一个新的模型文件,该文件将包含以下代码:

class SingletonDataModel: NSObject {

    var token:String?

    static let sharedInstance = SingletonDataModel()

    private override init() {
        super.init()
    }
} 
其次,从
ApppDelegate
类保存此上层模型的数据,如下所示:

var refreshedToken : String?

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    // refreshedToken is variable. I use it in viewcontroller.
    if let token = InstanceID.instanceID().token() {
        refreshedToken = token
        SingletonDataModel.sharedInstance.token = token
        print("InstanceID token: \(refreshedToken)")

    }
}
现在您的数据模型singleton已初始化,并且令牌值存储在该对象上

最后从
ViewController
Class
文件的
viewDidLoad
方法访问该值,如下所示:

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


    let token = SingletonDataModel.sharedInstance.token

    //Do your work


}

如果
token
nil
,这意味着在初始化
ViewController
之前,不会调用
AppDelegate
->
didRegisterForremotentificationswithDeviceToken
方法。您必须确保在初始化
ViewController
之前调用您的
didRegisterForRemoteNotificationsWithDeviceToken
。否则,您必须以不同的方式处理此问题

refreshedToken的数据类型是什么?@PaulMarshall Strings在应用程序委托上创建一个模型singleton,并在该模型上保存刷新令牌,然后从您的视图访问该singletonController@Md.Sulayman我该怎么做?我经常收到一个errorfunc应用程序(application:UIApplication,DidRegisterForRemotionTificationswithDeviceToken deviceToken:Data){如果var refreshedToken=InstanceID.InstanceID().token(){print(“InstanceID token:“refreshedToken”)}类ViewController:UIViewController{let token=AppDelegate.refreshedToken//Type'AppDelegate'没有成员'refreshedToken'。为什么?我的错误在哪里?……您没有在func中声明refreshedToken,而是将其声明为类的属性。class AppDelegate:UIResponder、UIApplicationDelegate、UNUserNotificationCenterDelegate{var window:UIWindow?var refreshedToken=InstanceID.InstanceID().token()..…类ViewController:UIViewController{let token=AppDelegate.refreshedToken Instance成员'refreshedToken'不能用于类型'AppDelegate',我不理解抱歉。检查解决方案,我已经发布了。这看起来像是为了很少的收益而做了很多额外的工作。为什么要从NSObject继承?不需要。由XCode自动生成。我知道这是额外的工作。question没有提到完整的流程/场景,我只是想提供帮助:)非常感谢,我有一个问题+token!线程1:致命错误:在展开可选值时意外发现nil。此全局变量是否有错误?在不需要时继承是一个坏习惯。感谢您的评论。这是一个错误。除非我需要,否则我通常不会继承。感谢@Joakim的评论
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.


    let token = SingletonDataModel.sharedInstance.token

    //Do your work


}