【问题标题】:SWIFT - Get values from userInfo to populate a fields of a Push NotificationSWIFT - 从 userInfo 获取值以填充推送通知的字段
【发布时间】:2018-11-30 14:15:41
【问题描述】:

我需要使用 userInfo 填充推送通知的字段(.title.body)。我尝试了一切,但我只能输入“日期”代码块。我能怎么做? 谢谢。

这是我从控制台 php 发送推送通知时的输出: OUTPUT

我在AppDelegate中的代码:

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
    //OTHER CODE
    let state = UIApplication.shared.applicationState
    if state == .background  || state == .inactive {
        let center = UNUserNotificationCenter.current()
        let content = UNMutableNotificationContent()
        let data = userInfo["data"] as! NSString //If i try to cast to NSDictionary, it will give me nil. Instead in this way i can see my output.
        print("DATA: \n\(data)\n")
        let title = ?? HELP
        let message = ?? ME!
        content.title = "\(title)"
        content.body = "\(message)"
        content.sound = .default
        let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 5, repeats: false)
        let request = UNNotificationRequest(identifier: "t", content: content, trigger: trigger)
        center.add(request, withCompletionHandler: nil)
    } else if state == .active {
        self.showAlertAppDelegate(title: "Okkey", message: "Test",imageName: "", buttonTitle: "OK", window: self.window!)
    }

【问题讨论】:

  • 请在控制台中分享您的打印数据,以便我们为您提供帮助..

标签: swift push-notification notifications apple-push-notifications push


【解决方案1】:

你可以试试

struct Root : Codable {
  let title:String
  let message:String
}

if let str = userInfo["data"] as? String {
   let res = try? JSONDecoder().decode(Root.self,from:str.data(using:.utf8)!)
   print(res?.title)
   print(res?.message)
}

【讨论】:

  • 老兄。非常感谢你。我快要疯了
【解决方案2】:

在您的用户信息中,您已经拥有一个字典! 你可以有你的标题和消息这样的

let title = userInfo["title"]
let message = userInfo["message"]

【讨论】:

  • op 表示数据中的内容,请务必同时转换类型
  • 是的,它已经在 userInfo 中了 :) 如果您尝试打印或调试 userInfo,您可以看到它
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-04-20
  • 1970-01-01
  • 2015-06-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多