Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get App Name in Swift

Tags:

swift

cocoa

How do I get the application name in Swift?

Googling gave me this:

[[[NSBundle mainBundle] infoDictionary] objectForKey:@"CFBundleName"]; 

I converted it to Swift; error - method doesn't exist:

NSBundle.mainBundle().infoDictionary.objectForKey("CFBundleName") 
like image 737
Kaatt Avatar asked Jan 31 '15 17:01

Kaatt


People also ask

How do I rename an app in Swift?

Build Settings> Change "Product Name" TARGETS> Select app> Change "Display Name" Project Navigator> Select project name> Double-click> Change "project name"> Rename> Mange Scheme> Change "Scheme name"

What is bundle display name?

The user-visible name for the bundle, used by Siri and visible on the iOS Home screen.


2 Answers

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 
like image 97
Grimxn Avatar answered Oct 15 '22 16:10

Grimxn


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) } 
like image 23
Vadim Bulavin Avatar answered Oct 15 '22 17:10

Vadim Bulavin