[英]Push Notifications Not Working Swift
因此,当我的应用当前未打开且收到推送通知时,横幅出现并按下时,“ didrecieveremotenotification”效果很好。 但是,当应用程序打开时,根本不会显示任何横幅。 我还希望在打开应用程序时也可以使用推送通知。
我尝试使用UNNotificationCenter,但总体上丢失了推送通知。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
UNUserNotificationCenter.current().delegate = self
UNUserNotificationCenter.current().requestAuthorization(options: [.badge, .sound, .alert], completionHandler: {(granted, error) in
if (granted) {
UIApplication.shared.registerForRemoteNotifications()
} else{
print("Notification permissions not granted")
}
})
}
//Called when a notification is delivered to a foreground app.
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void) {
completionHandler([.sound, .alert, .badge])
}
//Called to let your app know which action was selected by the user for a given notification.
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void) {
completionHandler()
}
更新: UNUserNotificationCenter.current().requestAuthorization
运行
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
授予权限时。
但是,当我不使用UNNotificationCenter并使用旧方法时,它不会失败。
为什么一种方法无法注册远程通知,而另一种却不能呢?
更新2:在模拟器中大声笑,这就是为什么它失败了。 但是,现在当我运行UNUserNotificationCenterDelegate
方法时,仅
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive
方法起作用,而不是
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent
更新3:我已经用尽所有可能的尝试。 什么将阻止代码触发willPresent
但didReceive
。 这是残酷的。 以前有没有人遇到过这个问题?
更新4:已解决。 我用于推送通知的服务要求用户与服务断开连接以发送推送通知。 当您在后台时,它会自动断开与您的连接,这就是为什么该方法起作用而它在前台不起作用的原因。
对于他们来说,这很奇怪,我可能会发送一封电子邮件。
在应用程序处于前台时,实现UNUserNotificationCenterDelegate
委托方法以获取通知(托盘在顶部)。 但它仅适用于IOS 10。
在您的didFinishLaunchingWithOptions
方法中,像这样设置UNUserNotificationCenterDelegate
委托。
UNUserNotificationCenter.current().delegate = self
实现委托方法...
//Called when a notification is delivered to a foreground app.
public func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Swift.Void) {
completionHandler([.sound, .alert, .badge])
}
//Called to let your app know which action was selected by the user for a given notification.
public func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Swift.Void) {
completionHandler()
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.