Get App Name in Swift

后端 未结 17 1821
被撕碎了的回忆
被撕碎了的回忆 2020-12-24 00:20

How do I get the application name in Swift?

Googling gave me this:

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


        
相关标签:
17条回答
  • 2020-12-24 00:41

    This should be more like what you are looking for:

    let infoDictionary: NSDictionary = NSBundle.mainBundle().infoDictionary as NSDictionary!
    let appName: NSString = infoDictionary.objectForKey("CFBundleName") as NSString
    
    NSLog("Name \(appName)")
    

    There may still be a better way to do this but it at least returns the app name correctly in my very limited testing...

    0 讨论(0)
  • 2020-12-24 00:41
    let bundleInfoDict: NSDictionary = NSBundle.mainBundle().infoDictionary!
    let appName = bundleInfoDict["CFBundleName"] as String
    
    0 讨论(0)
  • 2020-12-24 00:41

    Try this one,

    let bundleID = NSBundle.mainBundle().bundleIdentifier
    
    0 讨论(0)
  • 2020-12-24 00:43

    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 where possible, too:

    Bundle.main.infoDictionary![kCFBundleNameKey as String] as! String
    
    0 讨论(0)
  • 2020-12-24 00:44

    Swift 4

    let appName = Bundle.main.object(forInfoDictionaryKey: "CFBundleDisplayName") as! String

    0 讨论(0)
  • 2020-12-24 00:45
    let appDisplayName = Bundle.main.infoDictionary?["CFBundleName"] as? String
    

    It's optional, so put it in if let or guard statement.

    0 讨论(0)
提交回复
热议问题