6

当从某些 URL 方法打开 iOS 应用程序时,AppDelegates's会按这样的顺序调用:

1. - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

2. - (BOOL)application:(UIApplication *)application handleOpenURL:(NSURL *)url

如何在didFinishLaunchingWithOptions方法中知道应用程序是否从 URL 打开。可能有一些我想念的启动选项?

4

4 回答 4

9

您可以检查launchOptions传递给- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions.

Launch Options Keys在参考文档中查找部分,特别是UIApplicationLaunchOptionsURLKey

于 2013-07-31T11:26:08.290 回答
6

如果您的应用程序是从 URL 启动的,您会发现

UIApplicationLaunchOptionsURLKey 

launchOptions-的词典中(BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions

在相关说明中,该handleOpenURL:方法已被弃用,您应该使用:

-(BOOL)application:(UIApplication *)application openURL:(NSURL *)url sourceApplication:(NSString *)sourceApplication annotation:(id)annotation
于 2013-07-31T11:35:02.280 回答
1

首先,您应该实施application:didFinishLaunchingWithOptions:
检查 URL。如果你可以打开它,它应该返回 YES,如果你不能打开它,它应该返回 NO。

然后执行application:handleOpenURL:
Open URL。如果成功,它应该返回 YES 或 NO。

于 2013-07-31T11:38:47.203 回答
0

实际上,关于的答案UIApplicationLaunchOptionsURLKey是正确的,但并不完整。例如,如果用户在消息应用程序中点击通用链接并被重定向到您的应用程序,您会收到这些启动选项,而不是UIApplicationLaunchOptionsURLKey

[
    UIApplicationLaunchOptionsSourceApplicationKey: com.apple.MobileSMS,
    UIApplicationLaunchOptionsUserActivityDictionaryKey: [
         UIApplicationLaunchOptionsUserActivityKey: <NSUserActivity>,
         UIApplicationLaunchOptionsUserActivityTypeKey: NSUserActivityTypeBrowsingWeb
    ]
]

因此,要检查用户是否从 URL 登陆应用程序,在这种情况下您需要此代码:

let isFromUrl = ((launchOptions?[UIApplicationLaunchOptionsKey.userActivityDictionary] as? NSDictionary)?[UIApplicationLaunchOptionsKey.userActivityType] as? String == NSUserActivityTypeBrowsingWeb)

如果检查通过,则处理传入的 URL:

func application(_ application: UIApplication, continue userActivity: NSUserActivity, restorationHandler: @escaping ([Any]?) -> Void) -> Bool {
    if userActivity.activityType == NSUserActivityTypeBrowsingWeb {
        let url = userActivity.webpageURL
        // do your stuff ...
    }
return false
}
于 2019-04-10T13:56:53.230 回答