Search code examples
iosswift3appdelegateapn

How to pass data from appdelegate to a viewcontroller?


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)

Solution

  • OK - you've got most of the work already done...

    When using segues, iOS creates your view controller and gives you access to it in prepare, where you probably have done something like this:

    if let vc = segue.destination as? detailPinViewController {
         vc.myVariable = "this is the data to pass"  
    }
    

    In didFinishLaunchingWithOptions, you are doing the creation part, and the "presentation" part... so you can just add in the "pass the data" part:

    let destinationViewController = storyboard.instantiateViewController(withIdentifier: "detailPin2") as! detailPinViewController
    
    destinationViewController.myVariable = "this is the data to pass"
    
    let navigationController = self.window?.rootViewController as! UINavigationController
    
    navigationController.pushViewController(destinationViewController, animated: false)
    

    and that should do it.