在Swift中读取UIApplicationLaunchOptionsURLKey

只想阅读Swift中的启动选项。

这是我的旧obj-C代码,工作正常:

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { NSURL *URL = [launchOptions valueForKey:UIApplicationLaunchOptionsURLKey]; if (URL) 

这就是我认为Swift代码应该是这样的:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { if let options = launchOptions { let URL: NSURL = options(UIApplicationLaunchOptionsURLKey) as String 

但它给出了错误:

‘(NSString!) – > $ T2’与'[NSObject:AnyObject]’不同

铸造错误? 但难以正确地进行铸造而无法找到如何做到这一点的链接。

斯威夫特3:

在Swift 3中, launchOptions是一个类型为[UIApplicationLaunchOptionsKey: Any]?的字典[UIApplicationLaunchOptionsKey: Any]? ,所以你可以像这样访问这个值:

 launchOptions?[UIApplicationLaunchOptionsKey.url] 

由于密钥类型是UIApplicationLaunchOptionsKey ,因此您可以将enum类型简称为.url

 launchOptions?[.url] 

与该键关联的值是URL ,而不是String 。 此外,键可能不存在于字典中,因此您应该使用条件转换as? 而不是正常的铸造。

在Swift中,您想要:

 func application(_ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplicationLaunchOptionsKey: Any]?) -> Bool { if let url = launchOptions?[.url] as? URL { // If we get here, we know launchOptions is not nil, we know // key .url was in the launchOptions dictionary, and we know // that the type of the launchOptions was correctly identified // as URL. At this point, url has the type URL and is ready to use. } 

斯威夫特2:

在您的代码中, launchOptions是一个类型为[NSObject: AnyObject]?的字典[NSObject: AnyObject]? ,所以你想要访问这样的值:

 options?[UIApplicationLaunchOptionsURLKey] 

与该键关联的值是NSURL ,而不是String 。 此外,键可能不存在于字典中,因此您应该使用条件转换as? 而不是正常的铸造。

在Swift中,您想要:

 func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool { if let url = launchOptions?[UIApplicationLaunchOptionsURLKey] as? NSURL { // If we get here, we know launchOptions is not nil, we know // UIApplicationLaunchOptionsURLKey was in the launchOptions // dictionary, and we know that the type of the launchOptions // was correctly identified as NSURL. At this point, url has // the type NSURL and is ready to use. }