gpt4 book ai didi

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

转载 作者:搜寻专家 更新时间:2023-10-30 21:53:50 29 4
gpt4 key购买 nike

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

最佳答案

以下是我如何设置我的 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")
}
})

这将确定用户之前是否说过您的应用可以发送通知。如果不是,请按您喜欢的方式处理。

要在注册后访问设备 token :

//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()

}

关于swift - 当应用程序在前台时,如何处理 ios 推送通知?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42127403/

29 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com