如何将数据从 appdelegate 传递到视图控制器?

Jac*_*eXY 2 apn ios appdelegate swift3

您好,我正在尝试在我的 IOS 应用中实现推送通知功能。目前,如果应用程序是通过推送通知打开的,我的代码将打开特定的视图控制器。我这样做的方法是将视图控制器推到上面。

我现在需要做的是将一些数据从 appdelegate 传递给 viewcontroller。我知道将数据从视图控制器传递到视图控制器是使用prepareforsegue。我试过这样做,但没有用

我尝试研究如何完成这项任务,但很多关于 stackoverflow 的答案都是过时的 swift 代码,我无法转换为 swift 3。有人可以向我解释我如何将数据从 appdelegate 发送到视图控制器吗?

这是显示didFinishLaunchingWithOptions中的VC的代码

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)
Run Code Online (Sandbox Code Playgroud)

Igg*_*ggy 6

//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.
    }


}
Run Code Online (Sandbox Code Playgroud)