[英]How to pass data from appdelegate to a viewcontroller?
您好,我正在嘗試在IOS應用中實現推送通知功能。 目前,我有一些代碼,如果通過推送通知打開了應用程序,它將打開一個特定的viewcontroller。 我這樣做的方法是將ViewController推到頂部。
我現在需要做的是將數據從appdelegate傳遞到viewcontroller。 我知道將數據從viewcontroller傳遞到viewcontroller是使用prepareforsegue。 我嘗試這樣做,但是沒有用
我嘗試研究如何完成此任務,但是關於stackoverflow的許多答案都是過時的swift代碼,我無法轉換為swift3。有人可以向我解釋如何將數據從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)
//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.
}
}
好的-您已經完成了大部分工作...
使用segues時,iOS會創建您的視圖控制器,並允許您在prepare中對其進行訪問,在其中您可能已執行了以下操作:
if let vc = segue.destination as? detailPinViewController {
vc.myVariable = "this is the data to pass"
}
在didFinishLaunchingWithOptions
,您正在執行創建部分和“表示”部分...,因此您只需添加“傳遞數據”部分:
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)
那應該做到的。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.