2017-05-03 6 views
1

こんにちは私のIOSアプリケーションでプッシュ通知機能を実装しようとしています。現在、プッシュ通知によってアプリが開かれた場合、特定のviewcontrollerを開くコードがあります。私がこれをやっているのは、viewcontroller ontopを押すことです。appdelegateからviewcontrollerにデータを渡すには?

私が今必要とするのは、appcontrolからviewcontrollerにデータを渡すことです。私はviewcontrollerからviewcontrollerへのデータを渡すことを理解していますprepareforsegueを使用することです。私はこれをやってみましたがうまくいきませんでした。

私はこのタスクを取り込む方法を研究しましたが、stackoverflowに関する多くの回答は、私がswift 3に変換する能力がない時代遅れの古いコードでした。私はどのように私はviewcontrollerにappdelegateからデータを送信するのだろうか?

相続人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であるVCを表示するコード - あなたが既に行われた作業のほとんどを持っている...

seguesを使用する場合は、iOSのは、あなたのビューコントローラを作成します、didFinishLaunchingWithOptions

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

、あなたが作成部をやっていますし、あなたは、おそらくこのような何かをしたところ、準備それにアクセスすることができます"プレゼンテーション"パート... "データを渡す"の部分を追加するだけでよいでしょう:

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


} 
関連する問題