当应用未运行时如何处理推送通知?

问题描述 投票:0回答:1

我在项目中添加了onesignal,用于发送任何新闻通知,以在他们单击通知时向他们显示详细视图。当应用程序为前台或后台时,它运行良好,但是当应用程序未运行时,则无法运行。

我进行了研究,他们说,当应用未启动时,didRecieve方法不会调用。因此,我必须在didFinishLaunchingWithOptions方法中处理通知,我尝试过但相同。

AppDelegate.swift

import UIKit
import CoreData
import Firebase
import OneSignal
import GoogleMobileAds
import UserNotifications
import SDWebImageWebPCoder

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?
    var shortcutItemToProcess: UIApplicationShortcutItem?

    func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
        // Override point for customization after application launch.

        FirebaseApp.configure()

        GADMobileAds.sharedInstance().start(completionHandler: nil)

        let onesignalInitSettings = [kOSSettingsKeyAutoPrompt: false]
        OneSignal.initWithLaunchOptions(launchOptions,
        appId: "xxxxxxxxxxxxxxxxxxx",
        handleNotificationAction: nil,
        settings: onesignalInitSettings)
        OneSignal.inFocusDisplayType = OSNotificationDisplayType.notification
        OneSignal.promptForPushNotifications(userResponse: { accepted in
        })

        let WebPCoder = SDImageWebPCoder.shared
        SDImageCodersManager.shared.addCoder(WebPCoder)

        registerForPushNotifications()

        return true
    }

    func registerForPushNotifications() {

        let notificationCenter = UNUserNotificationCenter.current()
        notificationCenter.delegate = self

        let readAction = UNNotificationAction(identifier: "read", title: "Read", options: [.foreground])
        let closeAction = UNNotificationAction(identifier: "close", title: "Close", options: [])

        let category = UNNotificationCategory(identifier: "etkilesim", actions: [readAction, closeAction], intentIdentifiers: [], options: [])

        notificationCenter.setNotificationCategories([category])

        notificationCenter.requestAuthorization(options: [.alert, .sound, .badge]) {
            (granted, error) in
            guard granted else { return }
            DispatchQueue.main.async {
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }

    // MARK: UISceneSession Lifecycle

    func application(_ application: UIApplication, configurationForConnecting connectingSceneSession: UISceneSession, options: UIScene.ConnectionOptions) -> UISceneConfiguration {
        // Called when a new scene session is being created.
        // Use this method to select a configuration to create the new scene with.

        // Grab a reference to the shortcutItem to use in the scene
        if let shortcutItem = options.shortcutItem {
            shortcutItemToProcess = shortcutItem
        }

        return UISceneConfiguration(name: "Default Configuration", sessionRole: connectingSceneSession.role)
    }

}

extension AppDelegate: UNUserNotificationCenterDelegate {

    func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void) {

        completionHandler([.alert, .sound])
    }

    func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void) {

        var postId:String = ""
        var postType:String = ""

        if let custom = response.notification.request.content.userInfo["custom"] as? NSDictionary{
            if let a = custom["a"] as? NSDictionary{
                if let id = a["id"] as? String{
                    postId = id
                }
                if let type = a["rights"] as? String{
                    postType = type
                }
            }
        }

        if response.actionIdentifier == "read" {
            if postId != ""{
                NotificationCenter.default.post(name: NSNotification.Name("Detail"), object: nil, userInfo: ["id": postId, "type": postType])
            }
        }else if response.actionIdentifier == "close" {
            print("KAPAT")
        } else {
             if postId != ""{
                NotificationCenter.default.post(name: NSNotification.Name("Detail"), object: nil, userInfo: ["id": postId, "type": postType])
            }
        }
        completionHandler()
    }

}
ios swift swiftui onesignal
1个回答
0
投票

您必须向应用程序功能添加后台模式->远程通知,以便完全访问代理方法,例如:didReceiveRemoteNotification

我建议您将远程通知存储在链接到每个用户/设备的后端,并在每次应用启动时立即获取它们。这是确保数据一致性的唯一方法。

请检查this question

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.