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

时间:2017-02-09 02:51:33

标签: swift apple-push-notifications ios10 appdelegate

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

2 个答案:

答案 0 :(得分:8)

以下是我设置AppDelegate文件的方法:

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

import UserNotifications

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

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: [$0]) }.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()

}

答案 1 :(得分:1)

我将添加到havak5's answer中,您可以将推送通知设置为显示为iOS默认推送,如下所示:

交换代码:

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