关闭应用程序后如何在本地通知上打开VC

时间:2018-12-04 06:39:26

标签: ios swift localnotification unusernotificationcenter

嘿,我是iOS的新手,但我设法完成了一些任务。我正在为用户设置提醒的应用程序。因此,为此,我正在使用本地通知(UNUserNotificationCenterDelegate)。

一切正常。我已经编写了一些代码,正在计划的时间收到通知,并且已经处理了以下情况。

  • 应用程序在后台
  • 当应用程序处于前台时。

我的应用程序可以完美地处理这两种情况,或者您可以根据需要说。但在以下情况下我很无助

  

从最近删除该应用程序或什至不在其中运行该应用程序时   根本没有背景,那时候如果弹出计划通知,然后用户点击通知,它将打开启动视图控制器,然后打开我的应用主视图控制器,在这里我需要从用户设置提醒的预定时间。

我想我很清楚我想要什么和正在发生什么。是否有做任何更改。我知道这是可能的,因为Whats App和其他应用程序也在这样做。请帮助我做到这一点。 ...

注意: 我正在使用UserNotifications(本地通知),部署目标是10.3

更新: 我看到this链接与我的链接具有相同的需求,但是由于我是iOS新手,因此我不知道所选答案的建议,因此我不确定该怎么做:

2 个答案:

答案 0 :(得分:1)

当您的应用通过LocalNotification启动时,您的UNUserNotificationCenterDelegate方法userNotificationCenter didReceive response将被调用。

因此,我建议您像下面的方法一样在当前视图控制器顶部显示通知。

//Add this extension in any of your class
extension UIApplication {

@objc class func topViewController(_ base: UIViewController?) -> UIViewController? {

    var baseController = base

    if baseController == nil{

        baseController = UIApplication.shared.keyWindow?.rootViewController
    }

    if let nav = baseController as? UINavigationController {
        return topViewController(nav.visibleViewController)
    }

    if let tab = baseController as? UITabBarController {
        if let selected = tab.selectedViewController {
            return topViewController(selected)
        }
    }

    return baseController
}

}

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


    if response.actionIdentifier == "YourIdentifier"{

        let controllerToPresent = MyNotificationViewController(nibName: "MyNotificationViewController", bundle: nil)
        controllerToPresent.notificationInfo = response.notification.request.content.userInfo

        //If navigation flow needed, add controllerToPresent to nav controller
        let navConroller = UINavigationController(rootViewController: controllerToPresent)
        UIApplication.topViewController(nil)?.present(navConroller, animated: true, completion: nil)

        //If navigation flow not needed, present directly
        UIApplication.topViewController(nil)?.present(controllerToPresent, animated: true, completion: nil)
    }

    completionHandler()
}

答案 1 :(得分:1)

所以,您的问题是当应用程序被终止或处于非活动状态时,然后当用户点击通知时,将显示提醒屏幕,对吧?

情况是这样的: 通知显示(无效/已终止)->点击通知->启动->提醒屏幕。

您应该保存要在通知中显示的数据。 iOS会将所有通知数据保存在remoteNotification中。

因此,当用户从非活动状态打开应用程序时,将首先调用的是AppDelegate中的launchOption

这里是示例:

    if launchOptions != nil {
    // get data from notificaioton when app is killed or incative
           if let userInfo = launchOptions?[UIApplicationLaunchOptionsKey.remoteNotification] as? NSDictionary  {
                   // Do what you want, you can set set the trigger to move it the screen as you want, for your case is to reminder screen
                }
            }
相关问题