我需要使用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!)
}
答案 0 :(得分: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)
}
答案 1 :(得分:0)
在您的userInfo中,您已经有一个词典! 您可以在其中输入标题和消息
let title = userInfo["title"]
let message = userInfo["message"]