我在 App Delegate 中收到一条通知,其中包含数据(userInfo 变量)中的一个问题,我需要将此字符串传递给名为“Question”的 View Controller 。我希望这个字符串显示在问题 View Controller 中的这个变量 @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()
}
如何将数据传递给 View Controller ?我试图从那里访问变量,但没有成功。谢谢!
最佳答案
有很多方法可以解决这个问题。
您已经创建了一个 View Controller 并将其安装为窗口的 Root View Controller 。
使用这种方法,剩下的就是向目标 View Controller 添加一个字符串属性并设置该属性。然后将 question_view 转换为正确的类型并安装该属性。
最后,在您的 View Controller 的 viewWillAppear 中,将属性的值安装到 View 中:
class QuestionViewController: UIViewController {
public var questionString: String = ""
@IBOutlet weak var questionLabel: UILabel!
override func viewWillAppear(_ animated: Bool) {
questionLabel.text = questionString
}
}
适当修改您的应用程序委托(delegate)方法:
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
。
另请注意,您不应尝试直接引用 View Controller 的 View 对象。您应该使用我所展示的公共(public)字符串属性。
关于ios - 如何使用 Swift 将通知数据传递给 View Controller ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43953406/