我有一个应用程序,当用户与其他用户共享应用程序中的特定内容时,它使用深层链接导航到页面。当第二个用户已经运行应用程序时,这是有效的,但如果应用程序没有运行,它只是打开应用程序并保留在主屏幕上。我知道我一定在这里错过了一些非常简单的东西,但我就是想不通,在谷歌上找不到任何关于这个问题的答案。
我在应用程序委托中的代码.swift:
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {
let urlPath : String = url.path as String!
let urlHost : String = url.host as String!
let mainStoryboard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil)
if(urlHost != "example.com")
{
print("Call Not From Correct Host. Not Continuing...")
return false
}
if(urlPath == "/articles"){
let article: ArticleDetailsViewController = mainStoryboard.instantiateViewController(withIdentifier: "ArticleDetailsViewController") as! ArticleDetailsViewController
self.window?.rootViewController = article
}
self.window?.makeKeyAndVisible()
return true
}
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
return true
}
正确的行为。你应该在appliction(_: didFinishLaunchingWithOptions:)
处理它
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
// Override point for customization after application launch.
if let url = launchOptions[.url] as? URL, let annotation = launchOptions[.annotation] {
return self.application(application, open: url, sourceApplication: launchOptions[.sourceApplication] as? String, annotation: annotation)
}
return true
}
如果您使用的是 sceneDelegate,scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions)
函数将在终止状态后启动应用程序时起作用。
用于深度链接的 url 将在 connectionOptions.urlContext 中提供
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
navigateToDeepLinkScreen(urlContexts: connectionOptions.urlContexts)
}
对于 Swift4.2
if launchOptions != nil{
let launch = launchOptions![UIApplicationLaunchOptionsKey.userActivityDictionary]! as! Dictionary <String,Any>
if ((launch["UIApplicationLaunchOptionsUserActivityKey"]! as! NSUserActivity).webpageURL != nil){
if defaults.bool(forKey: DEFAULTS_IS_FIRST_START){
print((launch["UIApplicationLaunchOptionsUserActivityKey"]! as! NSUserActivity).webpageURL)
}
}
}
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if let url = launchOptions?[.url] as? URL {
return handleWidgetUrl(url)
}
return true
}
// Custom function to handle url and do some actions
private func handleWidgetUrl(_ url: URL) -> Bool {}
对于SceneDelegate
:
func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
/* some stuff */
for activity in connectionOptions.userActivities {
if let url = activity.webpageURL {
// handle
}
}
}