当应用程序关闭时,Swift 3 从 appdelget 呈现视图 [英] Swift 3 present view from appdelget when application was off

查看:26
本文介绍了当应用程序关闭时,Swift 3 从 appdelget 呈现视图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当用户打开推送通知时,我通过此代码显示来自 appdelget 的视图

when the user opening the push notification i present view from appdelget by this code

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"视图,然后在PostVC"视图顶部显示根视图!!所以你看不到PostVC"视图.

if the application is working the code run perfect but when the application is off it present "PostVC" view first and present the root-view on top of "PostVC" view!! so you can't see the "PostVC" view.

怎么了?但我不会使用 window?.makeKeyAndVisible()

what is wrong ? but i wouldn't to use window?.makeKeyAndVisible()

推荐答案

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

Ok! I give you an idea. Whenever the notification is fired and the user taps the notification, UNNotificationDefaultActionIdentifier will be called. Try this:

 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.

But as I suggested above open a childViewController instead.

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

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

I have not tested yet. Let me know if it's works! Good luck

这篇关于当应用程序关闭时,Swift 3 从 appdelget 呈现视图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆