使用App Delegate更新View Controller的变量

时间:2016-10-09 04:42:11

标签: ios swift firebase firebase-cloud-messaging

所以我基本上试图显示应用程序中收到的推送通知。 我正在尝试在收到通知时更新视图控制器的文本。但是,每次我尝试更新视图控制器时,都会收到错误:fatal error: unexpectedly found nil while unwrapping an Optional value

这是我的appdelegate片段:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
                 fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
    // If you are receiving a notification message while your app is in the background,
    // this callback will not be fired till the user taps on the notification launching the application.
    // TODO: Handle data of notification

    // Print message ID.

    print("Message ID: \(userInfo["gcm.message_id"]!)")



    let vc = FirstViewController()


    vc.notificationText = "Test"
    print (vc.notificationText)
    vc.updateText()

    // Print full message.
    print("%@", userInfo)
}

这是我的视图控制器:

class FirstViewController: UIViewController {


@IBOutlet weak var notificationLabel: UILabel!
var notificationText = "No notifications"

@IBAction func logOut(sender: AnyObject) {
    try! FIRAuth.auth()!.signOut()
    LogOutComplete()
}

func LogOutComplete() {
    let mainStoryboard = UIStoryboard(name: "Main", bundle: NSBundle.mainBundle())
    let logIn : UIViewController = mainStoryboard.instantiateViewControllerWithIdentifier("LogIn") as UIViewController
    self.presentViewController(logIn, animated: true, completion: nil)
}
override func viewDidLoad() {
    super.viewDidLoad()

    notificationLabel.text = notificationText

    //notificationLabel.text = notificationText
    // Do any additional setup after loading the view.
}

/*override func viewWillAppear(animated: Bool) {
    notificationLabel.text = notificationText
}*/

func updateText () {
    notificationLabel.text = notificationText
}

override func didReceiveMemoryWarning() {
    super.didReceiveMemoryWarning()
    // Dispose of any resources that can be recreated.
}
}

我真的不知道为什么它会给我这个错误。也许有人可以解释并帮助我解决问题。感谢所有帮助!

1 个答案:

答案 0 :(得分:2)

为Swift 2.2编辑:

您正在FirstViewController方法中创建application: didReceiveRemoteNotification的新实例。因此,您要更新FirstViewController的不同实例的属性,而不是您的意思。您正在更新的那个没有显示。错误即将发生,因为updateText()被调用但故事板未初始化,因此notificationLabel仍为零。

要执行您要执行的操作,请使用通知帖子将通知传递给视图控制器,并以观察者身份添加FirstViewController

AppDelegate中,将正文更改为以下内容:

func application(application: UIApplication, didReceiveRemoteNotification userInfo: [NSObject : AnyObject],
             fetchCompletionHandler completionHandler: (UIBackgroundFetchResult) -> Void) {
// If you are receiving a notification message while your app is in the background,
// this callback will not be fired till the user taps on the notification launching the application.
// TODO: Handle data of notification

// Print message ID.

print("Message ID: \(userInfo["gcm.message_id"]!)")
NotificationCenter.default.post(name: "Add_Notification_Post_Name_Here", object: nil,
                                                              userInfo: userInfo)

}

FirstViewController中,添加观察员以收听通知帖子:

override func viewWillAppear(_ animated: Bool) {
    super.viewWillAppear(animated)
    NotificationCenter.default.addObserver(self, selector: Some_Method_Name:, name: "Add_Notification_Post_Name_Here", object: nil)
}

FirstViewController中,添加处理此通知帖子的方法:

func Some_Method_Name(_ notification: NSNotification) {

guard let userInfo = notification.userInfo else {
        return
    }
    guard let payload = userInfo["Some_Message_Key_Here"] as? NSString  else {
        return
    }
    notificationText = String(payload)
    updateText()
}

此方法将您的包转换为String类型的有效内容,以分配给您的通知文本。然后调用updateText()函数。