Swift IOS: 从通知打开应用程序时调用 UIviewController 的特定功能

Swift IOS: Call Specific function of UIviewController when open app from notification

我想在应用程序打开时使用点击通知调用 onDidReceiveNotification 函数。 (ViewController 是第一个视图控制器,根视图控制器)

当应用程序打开或在后台时它工作正常,但是当应用程序未打开或在后台(不在内存中)并且当时点击打开应用程序时 onDidReceiveNotification 函数不被调用,

当使用点击推送通知打开应用程序时,我应该如何调用 onDidReceiveNotification 函数

ViewController.swift

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        NotificationCenter.default.removeObserver(self, name: .didReceiveAlert, object: nil)
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.onDidReceiveNotification(_:)), name: .didReceiveAlert, object: nil)
    }

@objc func onDidReceiveNotification(_ notification:Notification) {
        print("Received Notification")
    }
}

AppDelegate.swift

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {            
    NotificationCenter.default.post(name: .didReceiveAlert, object: nil)       
}

试试下面的代码

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    if let remoteNotif = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? [String: Any] {
         //call your notification method from here
         NotificationCenter.default.post(name: .didReceiveAlert, object: nil)  
    }
}

希望您在任何情况下都只需调用 didReceiveAlert 通知

在 AppDelegate 中检查您是否在 didReceiveRemoteNotification 中获得了负载。从那里您可以编写代码以推送到特定页面。

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any]) {
    // Print full message.
    print(userInfo)
    pushToPage(data: userInfo)
}

func pushToPage(data:[AnyHashable : Any]){
    print("Push notification received: \(data)")
    if let aps = data["aps"] as? NSDictionary {
        print(aps)
    }
}

当应用处于非活动状态并且用户点击通知时。在那种情况下,只有一个选项可以管理通知。

试试这个

在全局中创建一个变量 class 这样您就可以从任何地方访问它。

ExAppDelegate 中创建变量

var isNotificationTap : Bool = false

之后检查 launchOptions,如果 launchOptions 可用,则设置标志

if launchOptions != nil {
    if let userInfo = launchOptions?[UIApplication.LaunchOptionsKey.remoteNotification] as? [String : AnyObject] {
        if let dic = userInfo["body"] as? [String : AnyObject] {
            if let pushType = dic["push_type"] as? String {
                //Set Flag or any key in global file to identify that you tap on notification
                self.isNotifcaionTap = true
            }
        }
    }
}

然后只需检查 ViewController 中的标志。

class ViewController : UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()

        if self.isNotificationTap {

            print("Received Notification")
            //You can work with your notificaiton in inActive state
        }
    }

}

当应用打开或处于后台时调用 NotificationCenter.defalut.post,当应用处于 terminated/closed 并使用通知打开时获取实例并调用菜单 onDidReceiveAlert 函数,见以下代码。

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    if application.applicationState == .background || application.applicationState == .active {
        NotificationCenter.default.post(name: .didReceiveAlert, object: nil)
    }else {
        let nav = window?.rootViewController as! UINavigationController
        let mainVC = nav.viewControllers.first as! ViewController
        mainVC.onDidReceiveAlert(nil)
    }
}

或者直接从UINavigationController栈中获取ViewController实例,直接调用ViewController的函数(不需要Notification Observer)

func application(_ application: UIApplication, didReceiveRemoteNotification userInfo: [AnyHashable : Any], fetchCompletionHandler completionHandler: @escaping (UIBackgroundFetchResult) -> Void) {

    let nav = window?.rootViewController as! UINavigationController
    let mainVC = nav.viewControllers.first as! ViewController
    mainVC.onDidReceiveAlert(nil)       
}

创建带有可选参数的函数,使用以下代码。

@objc func onDidReceiveAlert(_ notification:Notification? = nil) {
    print("Received Notification")
}