【发布时间】: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