当应用程序关闭时,Swift 3 显示来自 appdelget 的 View

标签 swift ios10 appdelegate presentviewcontroller

当用户打开推送通知时,我通过此代码从 appdelget 呈现 View

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    application.applicationIconBadgeNumber = 0; // Clear badge when app is launched
    if UserDefaults.standard.bool(forKey: "PushOFF") == false
    {
        registerForRemoteNotification()
    }
    else
    {
        UIApplication.shared.unregisterForRemoteNotifications()
    }
    return true
}
func registerForRemoteNotification()
{
    if #available(iOS 10.0, *)
    {
        let center  = UNUserNotificationCenter.current()
        center.delegate = self
        center.requestAuthorization(options: [.sound, .alert, .badge]) { (granted, error) in
            if error == nil{
                UIApplication.shared.registerForRemoteNotifications()
            }
        }
    }
    else
    {
        UIApplication.shared.registerUserNotificationSettings(UIUserNotificationSettings(types: [.sound, .alert, .badge], categories: nil))
        UIApplication.shared.registerForRemoteNotifications()
    }
}

func application(_ application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: Data) {
    var token = ""
    for i in 0..<deviceToken.count {
        token = token + String(format: "%02.2hhx", arguments: [deviceToken[i]])
    }
    print("DEVICE TOKEN = \(token)")
}

func application(_ application: UIApplication, didFailToRegisterForRemoteNotificationsWithError error: Error)
{
    print("Registration failed! error=\(error)")
}
//Called when a notification is delivered to a foreground app.
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, willPresent notification: UNNotification, withCompletionHandler completionHandler: @escaping (UNNotificationPresentationOptions) -> Void)
{
    print("foreground User Info = ",notification.request.content.userInfo)
    completionHandler([.alert, .badge, .sound])
    print("foreground app",notification.request.content.userInfo)
}

//Called to let your app know which action was selected by the user for a given notification.
@available(iOS 10.0, *)
func userNotificationCenter(_ center: UNUserNotificationCenter, didReceive response: UNNotificationResponse, withCompletionHandler completionHandler: @escaping () -> Void)
{

    completionHandler()
    let result = response.notification.request.content.userInfo as! Dictionary<String, AnyObject>
    print("action User Info = ",result)

    let app = result["aps"] as! Dictionary<String, AnyObject>
    let title = app["alert"] as! String
    let id = result["id"]?.integerValue
    print("alert=",title,"id=",id!)
    if id != 0
    {
        if UserDefaults.standard.bool(forKey: "login")
        {
            UserDefaults.standard.set(title, forKey: "notificationTitle")
            UserDefaults.standard.set(id, forKey: "notificationId")
            UserDefaults.standard.synchronize()
            if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PostVC") as? UINavigationController
            {
                    var currentController = window?.rootViewController
                    while let presentedController = currentController?.presentedViewController
                    {
                        currentController = presentedController
                    }
                    currentController?.present(controller, animated: true, completion: nil)
            }
        }
    }
}

如果应用程序正在运行,则代码运行完美,但是当应用程序关闭时,它首先显示“PostVC” View ,并在“PostVC” View 之上显示 Root View !因此您看不到“PostVC” View 。

出了什么问题?但我不会使用 window?.makeKeyAndVisible()

最佳答案

好的!我给你一个主意。每当通知被触发并且用户点击通知时,UNNotificationDefaultActionIdentifier 就会被调用。试试这个:

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

    switch response.actionIdentifier {

    case UNNotificationDefaultActionIdentifier:

        DispatchQueue.main.async(execute: {
            openViewController()
        })

    default:
        break
    }

    completionHandler()
}

这将是你的功能:

func openViewController() {
    let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "PostVC") as? UINavigationController
    self.window?.rootViewController = controller
    self.window = UIWindow.init(frame: UIScreen.main.bounds)
    self.window?.makeKeyAndVisible()
}

但正如我上面建议的那样,打开一个 childViewController

 func openViewController() {

    let storyboard = UIStoryboard.init(name: "Main", bundle: nil)
    let rootViewController = storyboard.instantiateViewController(withIdentifier: "YourRootViewControllerIdentifier") as! UINavigationController
    let childViewController = storyboard.instantiateViewController(withIdentifier: "YourChildViewControllerIdentifier") as! YourCustomChildViewController

    rootViewController.pushViewController(childViewController, animated: true)

    self.window?.rootViewController = rootViewController
    self.window = UIWindow.init(frame: UIScreen.main.bounds)
    self.window?.makeKeyAndVisible()
}

我还没有测试过。让我知道它是否有效!祝你好运

关于当应用程序关闭时,Swift 3 显示来自 appdelget 的 View ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42552535/

相关文章:

ios - 从 StoryBoard 到 AppDelegate 引用 UITabBarController 的步骤

ios - AppDelegate 代码仅在后台运行

swift - NSViewController 未发布

ios - ViewController 的 Storyboard 助理编辑器打开 <projectName>-Swift.h 而不是 <viewController>.swift

swift - 如何在 AVAudioEngine 的点击中使用 AVAudioNodeTapBlock。

ios - 如何在SCNSphere对象上应用脉冲效果?

ios10 - map 注释在 ios10 中不显示

javascript - 使用自定义 URL 方案将数据从 UIWebView 发送回 iOS 应用程序会中断 Xcode 8/iOS 10

ios - 当应用程序进入前台时检测远程通知

swift - CAShapeLayer lineWidth 上未检测到点击事件?