当应用程序在前台时,如何处理 ios 推送通知?

How do I handle ios push notifications when the app is in the foreground?

如何设置我的 AppDelegate 以处理应用程序在前台和后台时发生的推送通知 swift 3 和 ios 10?包括如何让 phone 在我收到通知时在前台振动。

以下是我如何设置我的 AppDelegate 文件来执行此操作:

要处理推送通知,请导入以下框架:

import UserNotifications

要使 phone 在任何设备上振动,请导入以下框架:

import AudioToolbox

使您的 AppDelegate 成为 UNUserNotificationCenterDelegate:

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate, UNUserNotificationCenterDelegate {

在您的 "didFinishLaunchingWithOptions" 中添加:

    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")
        }
    })

这将确定用户之前是否说过您的应用可以发送通知。如果没有,请随意处理。

要在注册后访问设备令牌:

//Completed registering for notifications. Store the device token to be saved later
func application( _ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data ) {

    self.deviceTokenString = deviceToken.hexString
}

hexString 是我添加到项目中的扩展:

extension Data {
    var hexString: String {
        return map { String(format: "%02.2hhx", arguments: [[=15=]]) }.joined()
    }
}

处理您的应用在前台收到通知时发生的情况:

//Called when a notification is delivered to a foreground app.
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
    //Handle the notification
    //This will get the text sent in your notification
    let body = notification.request.content.body

    //This works for iphone 7 and above using haptic feedback
    let feedbackGenerator = UINotificationFeedbackGenerator()
    feedbackGenerator.notificationOccurred(.success)

    //This works for all devices. Choose one or the other. 
    AudioServicesPlayAlertSoundWithCompletion(SystemSoundID(kSystemSoundID_Vibrate), nil)
}

要处理当用户在您的应用程序处于后台时按下他们收到的(来自您的应用程序的)通知时发生的情况,请调用以下函数:

//Called when a notification is interacted with for a background app.
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
    //Handle the notification
    print("did receive")
    let body = response.notification.request.content.body
    completionHandler()

}

我要补充 havak5's answer,您可以将推送通知设置为显示为 iOS 默认推送,就像这样:

swift代码:

func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {
        if UIApplication.shared.applicationState == .active {
            completionHandler( [.alert,.sound]) // completionHandler will show alert and sound from foreground app, just like a push that is shown from background app
        }
    }