当我发送推送通知时,应用程序位于前台willPresent
被调用。永远不会调用didReceive
。当应用程序在后台并收到推送通知时,会显示警报,但应用程序从不会调用didReceive
或willPresent
。
在项目>功能,我检查了背景模式Location updates
和Remote notifications
。位置更新适用于不相关的代码。
我还启用了推送通知。这是正常的,因为他们正在收到。
我已在UNUserNotificationCenter
中实施了AppDelegate
通知内容,请参阅下文:
import UserNotifications
...
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {
...
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
...
registerForPushNotifications(application: application)
...
}
// MARK: - Push Notifications
func registerForPushNotifications(application: UIApplication) {
let notificationCenter = UNUserNotificationCenter.current()
notificationCenter.delegate = self
notificationCenter.requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in
if (granted)
{
UIApplication.shared.registerForRemoteNotifications()
}
else{
//Do stuff if unsuccessful...
print("Unsuccessful in registering for push notifications")
}
})
}
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
//convert the deviceToken to a string
let deviceTokenString = deviceToken.map { String(format: "%02.2hhx", arguments: [$0]) }.joined()
let ud = UserDefaults.standard
ud.set(deviceTokenString, forKey: "deviceToken")
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
//Handle the notification
print("User Info = ",notification.request.content.userInfo)
completionHandler([.alert, .badge, .sound])
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//handle the notification
print("Push notification: ",response.notification.request.content.userInfo)
... code to import the notification data into Core Data.
completionHandler()
}
...
}
为什么没有调用didReceive
的任何想法?
这是收到的推送通知:
[AnyHashable("aps"): {
alert = "[name] has added you as a friend.";
category = "NEWS_CATEGORY";
"related_user_id" = 55;
sound = default;
type = "friend_request";
}]
iOS 10.1,Swift 3。
答案 0 :(得分:6)
我发现获得许可后需要设置委托。
否则,当您第一次在应用程序中吃午餐时,您会在获得权限之前注册委托,并且didReceive函数不会触发-这仅在您第一次运行应用程序时发生,杀死并重新启动后就可以了。
见下文:
Tick
答案 1 :(得分:1)
didReceive 不会被执行,当用户对收到的通知执行操作时会执行该通知
来自https://peter.sh/experiments/chromium-command-line-switches/
的Apple文档要求您的应用知道用户为给定通知选择了哪个操作。
这意味着当用户对收到的通知执行操作时会调用此方法(按下通知,向下滑动等)
答案 2 :(得分:0)
如果您点按通知横幅,系统会调用willPresent
方法。
如果您希望在后台处理推送通知而无需点击横幅,则应将{" content-available":1}附加到通知有效负载。此类推送通知称为 silent 推送。这将不创建通知横幅/警报,就像正常推送一样,您必须自己创建横幅。
当您收到带有" content-available"的推送通知时,当应用在后台时,将调用didReceive
委托方法。
N.B。您还必须添加“远程通知”#39;在plist文件的UIBackgroundModes
键中。