推送通知不工作Swift

时间:2017-07-17 03:13:12

标签: ios push-notification

因此,当我的应用程序当前未打开且收到推送通知时," 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:已解决。我用于推送通知的服务要求用户与服务断开连接以发送推送通知。当你在后台时,它会自动断开你的连接,这就是为什么它有效并且它不在前台工作。

他们配置这种方式很奇怪,我可能会发送电子邮件。

1 个答案:

答案 0 :(得分:1)

在app处于前台时,实施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()
}