2017-05-03 159 views
1

你好,我正试图在我的IOS应用程序中实现推送通知功能。目前我有代码,如果通过推送通知打开应用程序,将打开一个特定的视图控制器。我这样做的方式是通过推动viewtopler ontop。如何将数据从appdelegate传递给viewcontroller?

我现在需要做的是将一些数据从appdelegate传递给viewcontroller。我明白从viewcontroller传递数据到viewcontroller是使用prepareforsegue。我试过这样做,但它没有工作

我试图研究如何完成这项任务,但很多在stackoverflow上的答案是过时的swift代码,我没有能力转换为swift 3.有人可以解释对我来说如何将数据从appdelegate发送到视图控制器?

继承人的代码,以显示VC是在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) 
+0

显示您正在使用的代码*显示AppDelegate中的VC。 – DonMag

+0

编辑帖子。代码现在应该是 – JackieXY

+0

我错过了什么吗?你在appdelegate中有一个函数,你有一个指向你的目标VC的指针。你不能用你打算通过的数据来调用你的VC的成员函数吗? – Spads

回答

1

OK - 你已经得到了大多数已经完成的工作的......

当使用塞格斯,iOS版创建您的视图控制器并且,您可以访问它的准备,你可能已经做了这样的事情:

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

didFinishLaunchingWithOptions,你正在做的制作部分,一个d的“演示”的一部分......所以你可以添加在“传递数据”部分:

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) 

而且应该这样做。

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


} 
相关问题