【问题标题】:Handle deep link notification处理深层链接通知
【发布时间】:2018-04-22 00:55:33
【问题描述】:

我正在向我的应用程序添加深层链接,并且在将 URL 传递给视图控制器时遇到了困难。我尝试使用通知,但它并不总是有效。

我的应用代表:

class AppDelegate: UIResponder, UIApplicationDelegate {
    var window: UIWindow?

    func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {  
        let notification = Notification(name: "DeepLink", object: url)
        NotificationCenter.default.post(notification)

        return true
    }
}

和视图控制器:

class ViewController: UIViewController {
    func viewDidLoad() {
        super.viewDidLoad()
        NotificationCenter.default.addObserver(self, selector: #selector(ViewController.handleDeepLink), name: "DeepLink", object: nil)
    }

    @objc private func handleDeepLink(notification: Notification) {
        let url = notification.object as! URL
        print(url)
    }
}

问题:当我的应用程序冷启动时,通知没有被处理,我猜这是由于 View Controller 还没有时间将自己注册为观察者。如果我按下 Home 按钮,转到 Notes 并再次单击深层链接,一切正常。

问题:如何注册 View Controller 以在应用冷启动时观察通知?或者有没有更好的方法将 URL 从 App Delegate 发送到 View Controller?

【问题讨论】:

    标签: swift deep-linking


    【解决方案1】:

    我认为最初的假设是假设您的视图控制器没有时间注册自己,这意味着 URL 和视图控制器之间的连接必须解耦并驻留在视图控制器之外。

    然后我会在收到 URL 时使用某种查找来实例化视图控制器。

    例如,

    if url.contains(“x”) {
      let vc = ViewController(...)
      cv.url = URL // Pass contextual data to the view controller.
      // Present or push cv
    }
    

    随着您的应用变得越来越复杂,您必须管理更具挑战性的场景,例如竖起整个控制器堆栈,或移除显示的控制器。

    【讨论】:

      【解决方案2】:

      我按照LaunchMe 应用程序中的示例进行操作。这就是解决我的问题的方法:

      func application(_ app: UIApplication, open url: URL, options: [UIApplicationOpenURLOptionsKey : Any] = [:]) -> Bool {
          // My root view controller is a UINavigationController
          // Cast this to whatever class your root view controller is
          guard let navigationController = self.window?.rootViewController as? UINavigationController else {
              return false
          }
      
          // Navigate to the view controller that handles the URL within the navigation stack
          navigationController.popToRootViewController(animated: false)
      
          // Handle the URL
          let vc = navigationController.topViewController as! ViewController
          vc.handleDeepLink(url: url)
          return true
      }
      

      【讨论】:

        【解决方案3】:

        如果未处理通知,则存储并在 viewDidLoad 时加载。

        var pendingNotificationInfo: PushNotificationInfo?
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2023-02-14
          • 1970-01-01
          相关资源
          最近更新 更多