ios - 在 Swift 中读取 UIApplicationLaunchOptionsURLKey

标签 ios objective-c iphone swift ios8

只是想阅读 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/

相关文章:

ios - 显示 URL 中的文件文档

iphone - 让 iOS 签名的应用程序在越狱设备上执行未签名的应用程序

iphone - 尝试重置/重新创建时,OpenFlow 使应用程序崩溃

android - 具有相同名称的不同应用程序?

ios - Reachability.h bool 变量 connectionRequired——这是什么意思?

ios - 是否可以将大框架的uiview添加到小框架的uiview中

ios - WatchOS 3 - 如何判断父应用程序是否在前台?

ios - 将二进制数据对象迁移到核心数据实体

objective-c - 让多个 NSScrollView 同时滚动

iphone - 为什么这个 iPhone 应用程序的 "quote"按钮没有替换 TextView 的 lorem ipsum?