如何在Swift中以编程方式获取捆绑标识符?

143

我该如何在Swift中获取Bundle ID?

Objective-C版本:

NSString *bundleIdentifier = [[NSBundle mainBundle] bundleIdentifier];
3个回答

298

试试这个:

let bundleID = NSBundle.mainBundle().bundleIdentifier

Swift 3+:

let bundleID = Bundle.main.bundleIdentifier

31
你知道为什么 bundleIdentifier 是可选类型吗?在哪些情况下它可能是 nil - Alexander
有时候在高级开发中,问题不在于它什么情况下可能为空,而是在底层哪些情况下可能为空。 - Sethmr
9
@Alexander 当它不是主要的捆绑包,或者 CFBundleIdentifier 缺失时。 - ArtFeel
@Alexander 对于未捆绑应用程序的主包和其info.plist文件中没有标识符条目的应用程序,它是nil。 - Andreas detests censorship
1
@Andreasdetestscensorship 哥们,我写那个已经7年了,时间过得真快。后来我遇到了这两种情况(Info.plist键名中的拼写错误和未捆绑的可执行文件)。很有道理!感谢分享。 - Alexander

14

在Swift中,基本上是相同的,只是类和方法名称被缩短了:

let bundleIdentifier = Bundle.main.bundleIdentifier // return type is String?

10

嘿,检查一下Swift3,移除你的负面检查。 - Ash

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接