【问题标题】:Updating variable of View Controller using App Delegate使用 App Delegate 更新 View Controller 的变量
【发布时间】:2016-10-09 04:42:11
【问题描述】:

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

这是我的 appdelegate sn-p:

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

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

【问题讨论】:

  • 你在使用界面生成器吗?
  • @Kex 故事板?是的
  • @NathanModern 这是因为您没有从情节提要中为视图控制器制作对象。您是否希望在推送到达时打开此视图控制器,或者当推送到达时您是否在此视图控制器上
  • 您正在 app main 中创建一个视图控制器,但实际上并没有引用在情节提要中创建的视图控制器。
  • 我希望在收到应用程序处于活动状态和关闭应用程序的推送通知时更新视图控制器。我希望它显示通知文本。我有一个连接到 ViewController 的故事板。 @Kex

标签: ios swift firebase firebase-cloud-messaging


【解决方案1】:

为 Swift 2.2 编辑:

您正在application: didReceiveRemoteNotification 方法中创建FirstViewController 的新实例。因此,您正在更新 FirstViewController 的另一个实例的属性,而不是您想要的。您正在更新的那个没有显示出来。错误即将到来,因为正在调用 updateText(),但情节提要未初始化,因此 notificationLabel 仍为 nil。

要做你想做的事,而是使用通知帖子将通知传递给视图控制器,并将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()
}

此方法将您的包转换为字符串类型的有效负载以分配给您的通知文本。然后你调用你的 updateText() 函数。

【讨论】:

  • @Ian Moses 这将在每次应用程序处于活动状态时创建一个新控制器
  • @NathanModern 这也许是让视图控制器处理从 appDelegate 收到的通知的正确方法。
  • @IanMoses 我应该在哪里添加 viewController 观察者?
  • 我一般在视图控制器的 viewWillAppear 方法中添加观察者。
  • 你能把它转换成 swift 2.2 吗?
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-24
  • 2018-06-11
  • 1970-01-01
  • 1970-01-01
  • 2017-06-27
相关资源
最近更新 更多