只是想阅读 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' is not identical to '[NSObject : AnyObject]'
类型转换错误?但很难正确转换,也找不到如何转换的链接。
最佳答案
swift 3:
在 Swift 3 中,launchOptions
是 [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.
}
swift 2:
在您的代码中,launchOptions
是一个类型为 [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.
}
关于ios - 在 Swift 中读取 UIApplicationLaunchOptionsURLKey,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26648894/