How to pass data from appdelegate to a viewcontroller?

JackieXY picture JackieXY · May 3, 2017 · Viewed 8.9k times · Source

Hello I am trying to implement a push notification feature in my IOS app. Currently I have code that will open a specific viewcontroller if the app was opened through the push notification. The way i'm doing this is by pushing the viewcontroller ontop.

What I need to do now is to pass some data to the viewcontroller from the appdelegate. I understand to pass data from viewcontroller to viewcontroller is to use prepareforsegue. I tried doing this and it did not work

I tried researching how to accompolish this task but a lot of the answers on stackoverflow were outdated swift code that I don't have the ability to convert to swift 3. can someone explain to me how would i send data from appdelegate to a viewcontroller?

heres the code to show the VC which is in didFinishLaunchingWithOptions

let storyboard = UIStoryboard(name: "Main", bundle: nil)

let destinationViewController = storyboard.instantiateViewController(withIdentifier: "detailPin2") as! detailPinViewController

let navigationController = self.window?.rootViewController as! UINavigationController

navigationController.pushViewController(destinationViewController, animated: false)

Answer

Iggy picture Iggy · May 4, 2017
//Declare you variable  somewhere within the app delegate scope
@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var myVariable: String = "Hello Swift"


    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.
        return true
    }
 // some other app delegate’s methods.... 

}

//In your view controller
class ViewController: UIViewController {

    @IBOutlet weak var myLabel: UILabel!
    let appDelegate = UIApplication.shared.delegate as! AppDelegate
    let myOtherVariable = appDelegate.myVariable

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        myLabel.text = myOtherVariable
        var anotherVariable: String = appDelegate.myVariable // etc...

    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }


}