如何从 ViewController 或其他地方调用或触发 AppDelegate 中的通知功能?

Posted

技术标签:

【中文标题】如何从 ViewController 或其他地方调用或触发 AppDelegate 中的通知功能?【英文标题】:How to call or trigger notification function in AppDelegate from ViewController or somewhere else? 【发布时间】:2016-06-16 12:33:38 【问题描述】:

我怎么能在ViewControllerappDelegate或其他地方调用这种方法:

func contactDelete(notification : NSNotification)

我必须在 appDelegate 内调用它

`didFinishLaunchingWithOptions` here or inside other classes:



      func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool 
            // Override point for customization after application launch.

            let tintColor = UIColor(red: 252/255, green: 72/255, blue: 49/255, alpha: 1)
            window!.tintColor = tintColor

            if let aLaunchOptions = launchOptions  // Checking if there are any launch options.
                // Check if there are any local notification objects.
                if let notification = (aLaunchOptions as NSDictionary).objectForKey("UIApplicationLaunchOptionsLocalNotificationKey") as? UILocalNotification 
                    // Handle the notification action on opening. Like updating a table or showing an alert.
                    UIAlertView(title: notification.alertTitle, message: notification.alertBody, delegate: nil, cancelButtonTitle: "OK").show()
  let root : UIViewController = self.window!.rootViewController! as UIViewController
                let alertview = JSSAlertView().show(root, title: "Oops!", text: "Unable to add the new Contact, check contact permission from Settings.", buttonText: "Check it", cancelButtonText: "Nope", color: UIColor.init(red: 0.216, green:0.043, blue:0.129, alpha: 1))
                alertview.addAction(contactDelete)
                alertview.setTextTheme(.Light)


                
            

它需要某种额外的参数,但我不知道是什么参数。我什至不能在viewDidLoad 方法中调用它。我试图像这样触发它,但它不起作用:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(ViewController.contactDelete(_:)), name:DELETECONTACT, object: nil)

【问题讨论】:

注册contactDelete函数处理什么样的通知? @PhillipMills 我正在使用 LocalNotificationHelper,所以我在 2 个地方使用它。一个地方是通知操作的位置,现在我必须在第二个函数中使用它 我的意思是:既然它是为响应通知而设计的,为什么不发送一个而不是直接调用它呢? 什么意思?如果我直接调用它,我必须发出很多通知。我也在 ViewController NSNotificationCenter.defaultCenter().addObserver(self, selector: "contactDelete:", name: DELETECONTACT, object: nil) 中这样称呼它 @PhillipMills 检查我的编辑。这是函数 【参考方案1】:

在您的 Appdelegate 代码中,您根据到达通知或简单启动分配 RootviewController:

if let notification = (aLaunchOptions as NSDictionary).objectForKey("UIApplicationLaunchOptionsLocalNotificationKey") as? UILocalNotification 

但是您将NotificationViewController 设置为rootViewController 并且您在MainViewController 上是addObserver,因此当您收到通知并且您的rootView 设置为NotificationViewController 时,您不会创建NSNotificationCenter 并且您将无法发布它。所以我建议创建如下代码:

你的 appdelegate didFinishLaunchingWithOptions 方法:

func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool 
        // Override point for customization after application launch.
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        let tintColor = UIColor(red: 252/255, green: 72/255, blue: 49/255, alpha: 1)
        window!.tintColor = tintColor

        application.registerForRemoteNotifications()
        application.registerUserNotificationSettings(UIUserNotificationSettings(forTypes: .Alert , categories: nil))


        let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier("first") as UIViewController


        let navController: UINavigationController = UINavigationController(rootViewController: initialViewControlleripad)
        navController.navigationBarHidden = true

        self.window?.rootViewController = navController
        self.window?.makeKeyAndVisible()


        let notification = launchOptions?[UIApplicationLaunchOptionsLocalNotificationKey] as! UILocalNotification!
        if (notification != nil) 


            runAfterDelay(2.0)   // add 2 second delay of call method open notificationViewController from mainViewController
                self.FireNewViewControlelr(notification.userInfo!)
            

        
        return true
    

以下是调用NotificationViewController的两种方法:

func FireNewViewControlelr(Value: [NSObject : AnyObject]) 

    print("userInf \(Value)")

    let navigationController: UINavigationController = (self.window!.rootViewController as! UINavigationController)
    let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
    let initialViewControlleripad : UIViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier("Main") as! NotificationViewController
    NSNotificationCenter.defaultCenter().postNotificationName(DELETECONTACT, object: Value)
    navigationController.pushViewController(initialViewControlleripad, animated: true)




func runAfterDelay(delay: NSTimeInterval, block: dispatch_block_t) 
    let time = dispatch_time(DISPATCH_TIME_NOW, Int64(delay * Double(NSEC_PER_SEC)))
    dispatch_after(time, dispatch_get_main_queue(), block)

如果您的应用处于后台模式,并且您通过点击 didReceiveLocalNotification 的通知横幅打开应用,则如下所示:

func application(application: UIApplication, didReceiveLocalNotification notification: UILocalNotification) 

        print("notification - tapped")

        if application.applicationState == UIApplicationState.Active 
            print("App already open")

         else 
            print("App opened from Notification")


            runAfterDelay(2.0) 
                self.FireNewViewControlelr(notification.userInfo!)
            

        

    

改代码如下:

 func FireNewViewControlelr(Value: [NSObject : AnyObject]) 

        print("userInf \(Value)")

        let navigationController: UINavigationController = (self.window!.rootViewController as! UINavigationController)
        let mainStoryboardIpad : UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
        let initialViewControlleripad : NotificationViewController = mainStoryboardIpad.instantiateViewControllerWithIdentifier("Main") as! NotificationViewController
        initialViewControlleripad.notificationInfo = Value
        navigationController.pushViewController(initialViewControlleripad, animated: true)

    

NotificationViewController

  var notificationInfo = [NSObject : AnyObject]()

    override func viewDidLoad() 
        super.viewDidLoad()


        print("data is \(notificationInfo)")


        // Do any additional setup after loading the view.
    

    override func didReceiveMemoryWarning() 
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    

    @IBAction func action(sender: AnyObject) 

         NSNotificationCenter.defaultCenter().postNotificationName(DELETECONTACT, object: notificationInfo)
       self.navigationController?.popToRootViewControllerAnimated(true)
    

【讨论】:

以上是关于如何从 ViewController 或其他地方调用或触发 AppDelegate 中的通知功能?的主要内容,如果未能解决你的问题,请参考以下文章

如何将变量从 ViewController 类传递给其他结构?

如何从viewcontroller转换到其他?

使图像可从其他 ViewController 访问

如何从其他 ViewController 向 TableViewController 添加复选标记

如何从共享类到ViewController获取JSON响应数据?

Swift ios 从任何地方展开到根 ViewController 选项卡