我正在使用 swift 创建一个 iOS 应用程序。我已经集成了用于推送通知的 onesignal SDK。现在我可以在应用程序处于前台时接收和管理通知。当应用程序处于后台时,我可以在通知面板中接收通知,但我无法在 appdelegate 中接收和管理它。在 appdelegate 中,当应用程序处于后台时,我在哪里可以接收通知?在这里我分享我的代码。我应该更改有效负载中的任何内容吗?
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
let notificationReceivedBlock: OSHandleNotificationReceivedBlock = { notification in
print("Received Notification: \(notification!.payload.notificationID)")
}
let notificationOpenedBlock: OSHandleNotificationActionBlock = { result in
// This block gets called when the user reacts to a notification received
let payload: OSNotificationPayload = result!.notification.payload
var fullMessage = payload.body
print("Message = \(fullMessage)")
if payload.additionalData != nil {
if payload.title != nil {
let messageTitle = payload.title
print("Message Title = \(messageTitle!)")
}
let additionalData = payload.additionalData
if additionalData?["actionSelected"] != nil {
fullMessage = fullMessage! + "\nPressed ButtonID: \(additionalData!["actionSelected"])"
}
}
}
let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false,
kOSSettingsKeyInAppLaunchURL: true]
OneSignal.initWithLaunchOptions(launchOptions,
appId: ONESIGNALAPP_I",
handleNotificationReceived: notificationReceivedBlock,
handleNotificationAction: notificationOpenedBlock,
settings: onesignalInitSettings)
OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification
return true
}
最佳答案
您需要在 AppDelegate 中实现这些方法:
extension AppDelegate {
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {
//use response.notification.request.content.userInfo to fetch push data
}
// for iOS < 10
func application(_ application: UIApplication, didReceive notification: UILocalNotification) {
//use notification.userInfo to fetch push data
}
func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {
//use userInfo to fetch push data
}
}
关于ios - 使用 OneSignal 在 iOS 中接收后台通知,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52560770/