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

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

我想通过点击通知打开应用程序时调用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)       
}
ios swift push-notification apple-push-notifications nsnotificationcenter
5个回答
1
投票

当应用程序打开或在后台调用NotificationCenter.defalut.post时,当应用程序终止/关闭并在当时使用通知打开时获取实例并通常调用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)
    }
}

或者只是从ViewController堆栈获取UINavigationController实例并直接调用ViewController的功能(Notification Observer not reqired)

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")
}

0
投票

试试下面的代码

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通知


0
投票

在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)
    }
}

0
投票

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

试试这个

在全局类中创建一个变量,以便您可以从任何地方访问它。

在AppDelegate中创建变量

var isNotificationTap : Bool = false

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

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
        }
    }

}

-1
投票

您可以通过使用控制器实例而不是notificationObserver来克服这种情况。

if let rootController = UIApplication.shared.keyWindow?.rootViewController{
        let controllerInstance = rootController.navigationController?.viewControllers[yourControllerIndex] as? ViewController
        controllerInstance.onDidReceiveNotification()
 }
© www.soinside.com 2019 - 2024. All rights reserved.