我正努力实现深度链接,以便在应用程序中导航到帖子。这是一个较旧的项目,因此我必须添加 SceneDelegate
类。只有当应用程序处于活动或后台状态时,深度链接实现才有效。如果应用程序尚未加载,则深度链接将无法使用。我看过许多帖子和教程,但仍然不清楚原因。有人遇到类似问题吗?
在 AppDelegate
类中,我已添加了以下函数的链接处理实现:
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey : Any]? = nil) -> Bool {}
func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {}
func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([UIUserActivityRestoring]?) -> Void) -> Bool {}
func application(_ application: UIApplication, open url: URL, sourceApplication: String?, annotation: Any) -> Bool {}
在
SceneDelegate
中,我实现了以下函数来处理链接:func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {}
func scene(_ scene: UIScene, openURLContexts URLContexts: Set<UIOpenURLContext>) {}
func scene(_ scene: UIScene, continue userActivity: NSUserActivity) {}
这些函数的实现看起来像这样:
let navigator = Navigator()
navigator.getDesination(for: url)
func getDesination(for url: URL){
let destination = Destination(for: url)
let ivc = InstantiateViewController()
switch destination {
case .post(let postID):
ivc.openPostVC(id: postID, showComment: true, commentID: nil)
case .user(let userID):
ivc.openProfileVC(userID: userID)
default:
break
}
}
enum Destination {
case post(Int)
case user(Int)
case feed(String)
case store
case safari
init(for url: URL){
if(url.pathComponents[1] == "p"){
self = .post(Int(url.pathComponents[2])!)
} else if(url.pathComponents[1] == "user") {
self = .user(Int(url.pathComponents[2])!)
} else if(url.pathComponents[1] == "store") {
self = .store
} else if(url.pathComponents[1] == "s") {
self = .feed(url.pathComponents[2])
} else {
self = .safari
}
}
}
func openProfileVC(userID: Int){
let service = UserPool.shared.request(for: userID)
let storyboard = UIStoryboard(name: "Profile", bundle: nil)
let profileVC = storyboard.instantiateViewController(withIdentifier: "ProfileView") as! ProfileViewController
profileVC.userService = service
profileVC.shouldNavigateToHome = true
profileVC.shouldNavigateToHomeAction = {
self.loadMainStoryboard()
}
let navigationVC = UINavigationController(rootViewController: profileVC)
navigationVC.view.backgroundColor = .white
if #available(iOS 13.0, *) {
guard let sceneDelegate = UIApplication.shared.connectedScenes.first?.delegate as? SceneDelegate else {return}
sceneDelegate.window?.rootViewController = navigationVC
sceneDelegate.window?.makeKeyAndVisible()
} else {
guard let appDelegate = UIApplication.shared.delegate as? AppDelegate else { return }
appDelegate.window?.rootViewController = navigationVC
appDelegate.window?.makeKeyAndVisible()
}
}
该网站的app-site-association文件如下,并已在Xcode中添加关联的域名:
{"applinks":{"apps":[],"details":[{"appID":"{my ID}","paths":["*"]}]},"webcredentials":{"apps":["{my ID}"]}}