问题描述
最低iOS版本为13,Scene delegate文件完全删除,只使用appdelegate。但是当使用深层链接打开应用时,open url
、continue userActivity
和 openURLContexts
方法不会调用。
func application(_ application: UIApplication,open url: URL,sourceApplication: String?,annotation: Any) -> Bool {
print("app opened using deep link from \(sourceApplication)")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "DeepLink"),object: nil,userInfo: nil)
return true
}
func application(_ application: UIApplication,continue userActivity:
NSUserActivity,restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
print("app opened using deep link ")
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "DeepLink"),userInfo: nil)
return true
}
func scene(_ scene: UIScene,openURLContexts URLContexts: Set<UIOpenURLContext>) {
if let url = URLContexts.first?.url{
print(url)
NotificationCenter.default.post(name: NSNotification.Name(rawValue: "DeepLink"),userInfo: nil)
}
}
编辑 - 1
Invalid redeclaration of 'application(_:open:options:)'
解决方法
这是我创建的一个 Sample App,用于在没有 SceneDelegate
的情况下在最低 iOS 13 中测试深层链接
这是因为您可能使用了错误的打开 URL 方法来接收深层链接:
正确的是:
func application(_ app: UIApplication,open url: URL,options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
print("Deep link received \(url)")
return true
}
continue userActivity 一般在通用链接的情况下调用
func application(_ application: UIApplication,continue userActivity: NSUserActivity,restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {
}
所以,AppDelegate 看起来像:
class AppDelegate: UIResponder,UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?) -> Bool {
return true
}
func application(_ app: UIApplication,options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
print("Deep link received \(url)")
return true
}
}
并在 Info.plist 中确保添加 URL Schemes。
<key>CFBundleURLTypes</key>
<array>
<dict>
<key>CFBundleURLName</key>
<string></string>
<key>CFBundleURLSchemes</key>
<array>
<string>deepLinks</string>
</array>
</dict>
</array>
然后要测试您的深层链接,请转到您的浏览器并使用 :// 编写您的 uri 方案
这种情况的例子:
deepLinks://mydeeplinkurl
它会要求你打开你的应用。
您将在打开 URL 方法中收到回调