打开通用链接时应用程序不在后台

9
我有一个类似的问题,与这个链接中的问题相同: iOS: apple universal link if app is not open? 当我点击通用链接时,如果应用程序不在后台,则无法进入func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {} 函数。 我在didFinishLaunchingWithOptions 中添加了一些代码。 但是它没有起作用。 如果有人能帮忙,非常感谢。
func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {

    let activityDic = launchOptions?[UIApplicationLaunchOptionsKey.userActivityDictionary]
    if activityDic != nil {
        // Continue activity here
        self.window?.rootViewController?.restoreUserActivityState(activityDic as! NSUserActivity)
    }


   return true
}

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
    if userActivity.activityType == NSUserActivityTypeBrowsingWeb {          
            if let controller = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "xxx") as? XXXTableViewController {
                if let window = self.window, let rootViewController = window.rootViewController {
                    var currentController = rootViewController
                    while let presentedController = currentController.presentedViewController {
                        currentController = presentedController
                    }
                    currentController.present(controller, animated: true, completion: nil)
                }
            }
    }

    return true

}
6个回答

11

将此代码放入didFinishLaunchingWithOptions函数中,以便在应用程序启动时打开URL(Swift 3代码):

    if let url = launchOptions?[UIApplicationLaunchOptionsKey.url] as? URL { //Deeplink
        // process url here
    }
    else if let activityDictionary = launchOptions?[UIApplicationLaunchOptionsKey.userActivityDictionary] as? [AnyHashable: Any] { //Universal link
        for key in activityDictionary.keys {
            if let userActivity = activityDictionary[key] as? NSUserActivity {
                if let url = userActivity.webpageURL {
                    // process url here
                }
            }
        }
    }

完美! - ElvinM
UIApplicationLaunchOptionsKey.url 什么情况下会不为空? - Will Calderwood

3

对于 IOS14 Swift 5,请使用SceneDelegate文件和函数。

func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Get URL components from the incoming user activity.
        guard let userActivity = connectionOptions.userActivities.first,
              userActivity.activityType == NSUserActivityTypeBrowsingWeb,
              let incomingURL = userActivity.webpageURL
        else { return }
        DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
            LinkHandler.sharedInstance.handleLink(url: incomingURL)
        }
        guard let _ = (scene as? UIWindowScene) else { return }
    }

2
    if let activityDic = launchOptions?[UIApplicationLaunchOptionsUserActivityDictionaryKey] {

        let options = activityDic.allValues.filter({ (option:AnyObject) -> Bool in

            return option is NSUserActivity
        })

        if options.count > 0 , let userActivity = options[0] as? NSUserActivity{
            // User activity handling should be done here 

        }

    }

如果您无法按常规方式访问'userActivity',请使用上述方法。


2

您可以在初始化时传递给应用程序的启动选项字典中访问URL。以下是在AppDelegate application(_:didFinishLaunchingWithOptions:)方法中实现的示例:

// Catch if open app from url
if let options = launchOptions {
    for key in options.keys {
        if(key == UIApplicationLaunchOptionsKey.url) {
            if let url = options[key] as? URL {
                AppDelegate.handleOpenURLWhenAppIsNotOpen(url)
            }
        }
    }
}

// or
if let url = launchOptions?[UIApplication.LaunchOptionsKey.url] as? URL {
    AppDelegate.handleOpenURLWhenAppIsNotOpen(url)
}

AppDelegate中,您需要使用以下方法:
private class func handleOpenURLWhenAppIsNotOpen(_ url: URL) {
     //can make what you like
}

谢谢您的回复。我尝试了,但它说AppDelegate没有成员handleOpenURLWhenAppIsNotOpen。如果我打错了,我很抱歉。 - ray
handleOpenURLWhenAppIsNotOpen是我的自定义方法,您可以在其中编写任何您喜欢的内容(例如在应用程序中呈现登录屏幕或其他屏幕)。在我的情况下,我初始化了tabBarController并选择了四个选项卡中的一个。 - Svetoslav Bramchev

1

Swift 4, 5(可行解决方案)

您可以尝试以下代码片段:

if let launchOptions = launchOptions, let dict = launchOptions[UIApplication.LaunchOptionsKey.userActivityDictionary] as? NSDictionary {
    if let userActivity = dict.first(where: { $0.value as? NSUserActivity != nil })?.value as? NSUserActivity {
       // handle your logic here
    }
}

0

我使用Branch.io来处理通用链接。以下代码仅供参考,如果有人需要。

func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool {
    // Override point for customization after application launch.
    //branch.io
    let branch: Branch = Branch.getInstance()
    branch.initSession(launchOptions: launchOptions, andRegisterDeepLinkHandler: {params, error  in
        // If the key 'pictureId' is present in the deep link dictionary
        if error == nil && params!["pictureId"] != nil {
            print("clicked picture link!")
            // load the view to show the picture
        } else {
            // load your normal view
        }
    })
    //branch io

    FBSDKApplicationDelegate.sharedInstance().application(application, didFinishLaunchingWithOptions: launchOptions) //don't put it on return
    return true
}

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
        // pass the url to the handle deep link call
        Branch.getInstance().continue(userActivity)

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接