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

3

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

现在我需要做的是从appdelegate向视图控制器传递一些数据。我了解到,要将数据从视图控制器传递到视图控制器,需要使用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)

展示你在AppDelegate中使用的代码来显示VC。 - DonMag
修改过的帖子。代码现在应该已经上传了。 - JackieXY
我有什么遗漏吗?你正在appdelegate的一个函数内部,并且你有指向目标VC的指针。你不能调用你的VC的成员函数并传递你想要传递的数据吗? - adamfowlerphoto
2个回答

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


}

这段代码显示了一个错误:无法在属性初始化器中使用实例成员'appDelegateView';属性初始化器在'self'可用之前运行。 - Khris Vandal

1

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

在使用转场时,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)

那就这样吧。


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接