我遇到了一个大问题,我在iOS项目上设置了推送通知(非常困难)。我决定在"AppDelegate"的"didReceiveRemoteNotification"方法中接收通知的数据,然后以编程方式创建它(以便进行强制性的个人处理)。一切都很完美,只有当我在没有Xcode帮助的情况下启动应用程序时,我不再收到通知,通知创建代码也不会执行。我不知道该怎么办。。。
func application(_ application: UIApplication,
didReceiveRemoteNotification userInfo: [AnyHashable: Any],
fetchCompletionHandler completionHandler: @escaping
(UIBackgroundFetchResult) -> Void) {
let body = userInfo["body"]
print(userInfo)
if #available(iOS 10.0, *) {
let content = UNMutableNotificationContent()
content.body = body! as! String
let trigger = UNTimeIntervalNotificationTrigger(timeInterval:
1, repeats: false)
let request = UNNotificationRequest(identifier: "idt", content:
content, trigger: trigger)
UNUserNotificationCenter.current().add(request,
withCompletionHandler: nil)
} else {
// Fallback on earlier versions
}
completionHandler(UIBackgroundFetchResult.newData)
}
非常感谢
从通知启动应用程序时,需要检查application:didFinishLaunchingWithOptions:
中的启动选项,以查看是否存在UIApplicationLaunchOptionsRemoteNotificationKey
。
根据文件:
此密钥的值是包含远程通知有效负载的NSDictionary。有关处理远程通知的更多信息,请参阅应用程序的描述:didReceiveRemoteNotification。该键还用于访问名为UIApplicationDidFinishLaunchingNotification的通知的userInfo字典中的相同值。
确定启动包含通知后,使用从launchOptions获得的通知有效负载调用通知处理程序方法。
您现在拥有的application(_:didReceiveRemoteNotification:)
只有在应用程序已经运行时才会触发:
如果应用程序正在运行,应用程序会调用此方法来处理传入的远程通知。userInfo字典包含aps密钥,该密钥的值是具有剩余通知的另一个字典
您需要检查项目设置/功能-后台模式-远程通知
在功能中启用远程通知。
{
"aps" : {
"content-available" : 1,
"badge" : 0,
"Priority" : 10
},
"acme1" : "bar",
"acme2" : 42
}
通知的优先级:
10推送信息会立即发送。
远程通知必须在设备上触发警报、声音或徽章。将此优先级用于仅包含content-available
密钥的推送是错误的。
https://developer.apple.com/library/archive/documentation/NetworkingInternet/Conceptual/RemoteNotificationsPG/BinaryProviderAPI.html#//apple_ref/doc/uid/TP40008194-CH13-SW1
当设备运行并连接到Xcode时,系统会将静默通知视为高优先级,因为操作系统足够智能,可以知道"你必须调试你的应用程序,所以我会将你的应用任务视为高优先权"。
当设备与Xcode断开连接时,系统会将静默通知视为低优先级。因此,它不能保证它们的交付以提高电池寿命。