2017-05-13 19 views
0

App Delegateでデータ内の質問(userInfo変数)で通知を受け取り、この文字列をView Controllerに渡す必要があります。この文字列をこの変数に表示します。@IBOutlet弱い質問:UILabel!は質問表示コントローラにあります。Swiftで通知コントローラに通知データを渡す方法

func userNotificationCenter(_ center: UNUserNotificationCenter, 
          didReceive response: UNNotificationResponse, 
          withCompletionHandler completionHandler: @escaping() -> Void) { 
    let userInfo = response.notification.request.content.userInfo 
    // Print message ID. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("Message ID: \(messageID)") 
    } 

    // Print full message. 
    print(userInfo) 
    let storyboard = UIStoryboard(name:"Main", bundle:nil) 
    let question_view = storyboard.instantiateViewController(withIdentifier: "Question") 
    window?.rootViewController = question_view 

    completionHandler() 
} 

どのようにデータをView Controllerに渡すことができますか?私はそこから変数にアクセスしようとしましたが、うまくいきませんでした。ありがとう!

+0

[View Controller間でデータを受け渡しする]の可能な複製(http://stackoverflow.com/questions/5210535/passing-data-between-view-controllers) – thewaywewere

答えて

1

これを処理する方法はたくさんあります。

すでにビューコントローラを作成しており、これをウィンドウのルートビューコントローラとしてインストールしています。

このアプローチでは、ターゲットビューコントローラに文字列プロパティを追加し、そのプロパティを設定するだけです。次に、question_viewを正しいタイプにキャストしてプロパティをインストールします。

最後に、あなたのビューコントローラのviewWillAppearで、ビューにプロパティの値をインストールします。

class QuestionViewController: UIViewController { 

    public var questionString: String = "" 
    @IBOutlet weak var questionLabel: UILabel! 

    override func viewWillAppear(_ animated: Bool) { 
     questionLabel.text = questionString 
    } 
} 

、アプリのデリゲートメソッド、適宜変更:

func userNotificationCenter(_ center: UNUserNotificationCenter, 
          didReceive response: UNNotificationResponse, 
          withCompletionHandler completionHandler: @escaping() -> Void) { 

    //Use a guard statement to make sure that userInfo is a String 
    guard let userInfo = response.notification.request.content.userInfo as? String else { 
     completionHandler() 
     return 
    } 

    // Print message ID. 
    if let messageID = userInfo[gcmMessageIDKey] { 
     print("Message ID: \(messageID)") 
    } 

    // Print full message. 
    print(userInfo) 
    let storyboard = UIStoryboard(name:"Main", bundle:nil) 
    //If question_view is the correct type, set it's question_string property 
    if let question_view = storyboard.instantiateViewController(withIdentifier: "Question") as QuestionViewController { 
     questionString = userInfo 
    window?.rootViewController = question_view 

    completionHandler() 
} 

注そのような変数名question_viewは、SwiftでcamelCaseを使用する必要があります。あなたはsnake_caseを使用していますが、これは規約ではありません。あなたの名前はquestion_viewは本当にquestionViewになるはずです。

また、ビューコントローラのビューオブジェクトを直接参照しないでください。私が示したように、パブリックの文字列プロパティを使用する必要があります。

+0

ありがとうございます!それは働いている! –

+0

あなたの質問に答えた場合は、私の答えを受け入れるべきです。十分な評判が得られたら、高品質の回答とみなす投票投票の回答も考慮する必要があります。 (最初の正解を受け入れることは、このサイトの必須条件です。上向き投票はオプションですが、奨励されます) –

+0

完了!再度、感謝します :) –