如何将数据从 appdelegate 传递到 viewcontroller?

How to pass data from appdelegate to a viewcontroller?

您好,我正在尝试在我的 IOS 应用程序中实现推送通知功能。目前,如果应用程序是通过推送通知打开的,我的代码将打开一个特定的 viewcontroller。我这样做的方法是将 viewcontroller 推到顶部。

我现在需要做的是将一些数据从 appdelegate 传递给 viewcontroller。我了解将数据从 viewcontroller 传递到 viewcontroller 是使用 prepareforsegue。我尝试这样做但没有成功

我试着研究如何完成这个任务,但是 Whosebug 上的很多答案都过时了 swift 我没有能力转换成的代码 swift 3. 有人能解释一下吗对我来说,我如何将数据从 appdelegate 发送到 viewcontroller?

这里是显示 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)

好的 - 你已经完成了大部分工作...

当使用 segues 时,iOS 会创建你的视图控制器并让你在准备阶段访问它,你可能已经做过这样的事情:

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

didFinishLaunchingWithOptions 中,您正在进行创建部分,而 "presentation" 部分...因此您可以在 "pass the data" 部分中添加:

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)

应该就可以了。

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


}