SWIFT - Получить значения из userInfo для заполнения полей Push-уведомления - PullRequest
0 голосов
/ 30 ноября 2018

Мне нужно заполнить поля push-уведомлений (.title и .body), используя userInfo.Я перепробовал все, но я могу только ввести блок кода "дата".Как я могу сделать?Спасибо.

Это мой вывод, когда я отправляю push-уведомление с моей консоли 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!)
    }

Ответы [ 2 ]

0 голосов
/ 30 ноября 2018

В вашем userInfo у вас уже есть словарь!Вы можете иметь свой заголовок и сообщение ike this

let title = userInfo["title"]
let message = userInfo["message"]
0 голосов
/ 30 ноября 2018

Можно попробовать

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