appdelegate swift4中的全局变量

时间:2018-04-21 10:25:02

标签: 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?

4 个答案:

答案 0 :(得分:1)

您需要了解声明变量的范围以及它在该范围之外的可见性。现在你的变量只在那个func中可见,为了使它对你的视图控制器可见,它需要是AppDelegate中的一个类属性。

所以定义一个属性(这里有一些简化的代码)

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

}

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

let token = appDelegate.refreshedToken

答案 1 :(得分:0)

只需在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)")

        }
    }
}

从上面的代码中,如果didRegisterForRemoteNotificationsWithDeviceToken方法被调用,则refreshedToken可用,否则它将为nil。

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

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

答案 2 :(得分:0)

您可以在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")

       }
}

和以后可以使用

检索ViewController中的值
let postString = "ajax=token&"+"token="+  UserDefaults.standard.string(forKey: "Key")

答案 3 :(得分:0)

您可以使用Singleton Model Object处理此问题,该对象将保存您的数据,并可以从项目的任何位置全局访问数据。

首先创建一个新的模型文件,其代码如下:

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)")

    }
}

现在,您的数据模型单例已初始化,令牌值存储在该对象

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

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


}

如果tokennil,则表示您的AppDelegate - >在didRegisterForRemoteNotificationsWithDeviceToken初始化之前,不会调用ViewController方法。您必须确保在didRegisterForRemoteNotificationsWithDeviceToken初始化之前调用ViewController。否则你必须以不同的方式处理这个