Read UIApplicationLaunchOptionsURLKey in Swift

2019-06-15 20:12发布

问题:

Simply want to read the launch options in Swift.

This is my old obj-C code which worked fine:

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

this is what I think the Swift code should look like:

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

but it gives the error:

'(NSString!) -> $T2' is not identical to '[NSObject : AnyObject]'

A casting error? but having difficulty casting it properly and can't find links for how to do it.

回答1:

Swift 3:

In Swift 3, launchOptionsis a dictionary of type [UIApplicationLaunchOptionsKey: Any]?, so you'd access the value like this:

launchOptions?[UIApplicationLaunchOptionsKey.url]

Since the key type is UIApplicationLaunchOptionsKey, you can abbreviate the enum type as simply .url:

launchOptions?[.url]

The value associated with that key is a URL though, and not a String. Also, the key might not be present in the dictionary, so you should use conditional casting as? instead of normal casting.

In Swift, you want to do:

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:

In your code, launchOptions is a dictionary of type [NSObject: AnyObject]?, so you'd want to access the value like this:

options?[UIApplicationLaunchOptionsURLKey]

The value associated with that key is an NSURL though, and not a String. Also, the key might not be present in the dictionary, so you should use conditional casting as? instead of normal casting.

In Swift, you want to do:

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.
    }