Get App Name in Swift

Solution 1:

This should work:

NSBundle.mainBundle().infoDictionary!["CFBundleName"] as! String

infoDictionary is declared as a var infoDictionary: [NSObject : AnyObject]! so you have to unwrap it, access it as a Swift dictionary (rather than use objectForKey), and, as the result is an AnyObject, cast it.

Update Swift 3 (Xcode 8 beta 2)

Always better to use constants (and optionals) where possible, too:

Bundle.main.infoDictionary?[kCFBundleNameKey as String] as? String

Solution 2:

I believe this solution is more elegant. What's more, using object(forInfoDictionaryKey:) is encouraged by Apple:

"Use of this method is preferred over other access methods because it returns the localized value of a key when one is available."

extension Bundle {
    var displayName: String? {
        return object(forInfoDictionaryKey: "CFBundleDisplayName") as? String
    }
}

Accessing bundle display name:

if let displayName = Bundle.main.displayName {
    print(displayName)
}

Solution 3:

I have created a simple extension to get the app name that is shown under the icon on the Home screen.

By default, apps only have CFBundleName set. Some apps, however, set CFBundleDisplayName (The user-visible name of the bundle) to change the title under the app icon. Adding spaces is often the case, e.g. bundle name "ExampleApp" could have bundle display name set to "Example App".

extension Bundle {
    // Name of the app - title under the icon.
    var displayName: String? {
            return object(forInfoDictionaryKey: "CFBundleDisplayName") as? String ??
                object(forInfoDictionaryKey: "CFBundleName") as? String
    }
}

Usage:

let appName = Bundle.main.displayName

Solution 4:

Same answer in Swift 4.2

extension Bundle {
    static func appName() -> String {
        guard let dictionary = Bundle.main.infoDictionary else {
            return ""
        }
        if let version : String = dictionary["CFBundleName"] as? String {
            return version
        } else {
            return ""
        }
    }
}

you can use it like below

let appName = Bundle.appName()

Hope this helps :)