我目前正在将我的应用程序从Objective-C重写为Swift,并正在处理通知。出于某种原因,该应用程序的Swift版本未收到任何Objective-C版本的远程推送通知。
这是我用来在AppDelegate中注册通知的代码:
UNUserNotificationCenter.current().delegate = self
let options: UNAuthorizationOptions = [.badge, .alert, .sound]
UNUserNotificationCenter.current().requestAuthorization(options: options, completionHandler: { granted, error in
print("access granted: \(granted)")
})
application.registerForRemoteNotifications()
我假设该应用程序成功注册,因为调用了didRegisterForRemoteNotificationsWithDeviceToken
方法。但是,当我尝试使用从该方法获得的令牌发送测试通知时,我没有在设备上收到实际的通知。
这些方法都不被调用:
func pushRegistry(_ registry: PKPushRegistry, didReceiveIncomingPushWith payload: PKPushPayload, for type: PKPushType) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, openSettingsFor notification: UNNotification?) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (_ options: UNNotificationPresentationOptions) -> Void) {
}
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
}
func application(_ application: UIApplication, handleActionWithIdentifier identifier: String?, forRemoteNotification userInfo: [AnyHashable : Any], completionHandler: @escaping () -> Void) {
}
我在做什么错了?
答案 0 :(得分:0)
您说您没有收到,所以首先确保您之前提到的那些未被调用的方法是从这里extension AppDelegate: UNUserNotificationCenterDelegate
来的(顺便说一句,当您实现 didReceive 方法,请确保在最后调用completionHandler()
执行此操作时:
application.registerForRemoteNotifications()
确保从主线程运行它,因为如果未从后台指定它,则可以调用它,否则可能会失败。您可以这样做
DispatchQueue.main.async {
UIApplication.shared.registerForRemoteNotifications()
}
我假设您是以这种方式或类似的方式获取设备令牌:
func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
// 1. Convert device token to string
let tokenParts = deviceToken.map { data -> String in
return String(format: "%02.2hhx", data)
}
let token = tokenParts.joined()
// 2. Print device token to use for PNs payloads
print("Device Token: \(token)")
}
最后实现此方法以查看注册设备时是否有任何错误
func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error) {
// 1. Print out error if PNs registration not successful
print("Failed to register for remote notifications with error: \(error)")
}
哦,顺便说一句(以防万一您错过了它),请确保在项目目标中启用了推送通知。
答案 1 :(得分:0)
确保在项目设置功能中启用了推送通知。 如何启用: 转到目标:->选择项目->转到功能->转到推送通知。在那里启用它。
另一件事是证书。在开发过程中,您不应获得生产证书。