【问题标题】:How to pass notification data to a View Controller with Swift如何使用 Swift 将通知数据传递给视图控制器
【发布时间】:2017-10-12 16:46:18
【问题描述】:

我在 App Delegate 中收到一条通知,其中包含数据中的问题(userInfo 变量),我需要将此字符串传递给名为“问题”的视图控制器。我希望这个字符串显示在问题视图控制器中的这个变量 @IBOutlet weak var question: UILabel! 中。

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()
}

如何将数据传递给视图控制器?我试图从那里访问变量,但我没有工作。谢谢!

【问题讨论】:

标签: ios swift uiviewcontroller notifications appdelegate


【解决方案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 中应该使用驼峰命名法。您使用的是snake_case,这不是惯例。你的名字question_view 应该是questionView

还请注意,您不应尝试直接引用视图控制器的视图对象。你应该使用我展示的公共字符串属性。

【讨论】:

  • 如果它回答了您的问题,您应该接受我的回答。一旦您有足够的声誉,您还应该考虑对您认为是高质量答案的答案进行投票。 (接受第一个正确答案几乎是本网站的一项要求。投票是可选的,但鼓励。)
  • 完成!!再次感谢:)
猜你喜欢
  • 2018-03-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-12-28
  • 1970-01-01
  • 2021-12-07
  • 1970-01-01
相关资源
最近更新 更多