Swift Passing data from appDelegate to another class

MeV picture MeV · Nov 3, 2014 · Viewed 16.8k times · Source

I need to pass a variable from the AppDelegate to another class that I have created to hold global variables of the project and I'm not able to find a way to make it work.

This is the code in the AppDelegate:

func application(application: UIApplication!, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData!) {
    println("Device's token is: \(deviceToken)")

    //Global Variables Class Instance
    let globals:Globals = Globals()

    globals.setDeviceToken("test1") //method1 not working
    globals.deviceToken = "test2"   //method2 not working
}

This is my Globals Class:

public class Globals {
    var deviceToken = String()

    init() {
        //nothing
    }

    func setDeviceToken(s:String){
        deviceToken = s
    }

    func getDeviceToken() -> String {
        return deviceToken
    }
}

If i try to print the value, from other files of the project, I'm not able to get anything, just an empty string.

class ViewController: UIViewController {

    //Global Variables Class Instance
    let globals:Globals = Globals()

    override func viewDidLoad() {
        println(globals.getDeviceToken())  //return empty string
        println(globals.deviceToken)       //return empty string

Answer

Bob Vork picture Bob Vork · Nov 3, 2014

There are several patterns you can use to achieve what you want

  1. You could access the AppDelegate through the UIApplication:

    let delegate = UIApplication.sharedApplication().delegate as AppDelegate
    let deviceToken = delegate.deviceToken
    
  2. Look into singletons. A quick google search for 'Swift singleton' will get you a long way. The first result:

    class SingletonB {
    
            class var sharedInstance : SingletonB {
            struct Static {
                static let instance : SingletonB = SingletonB()
            }
            return Static.instance
        }
    }
    

Then use sharedInstance to instantiate the singleton anywhere and access the same variables.

The first one is quick and dirty, so for more serious projects I would recommend the singleton pattern.

There are probably a million ways to do this, but this should get you started

(More at this link, which explores a few ways to implement singletons: https://github.com/hpique/SwiftSingleton )