作者:回味的微笑_184 | 来源:互联网 | 2023-02-12 14:49
如何设置我的AppDelegate来处理应用程序在前台和后台使用swift 3和ios 10时发生的推送通知?如果我收到通知,包括如何让手机在前台振动.
1> havak5..:
以下是我设置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()
}