所以我有一个主要的iOS应用程序,其中包括我创建的框架。
在这个框架中,我创建了一个可本地化的助手和一个日期助手。日期助手有一个函数timeAgo(),它可以返回"8小时前“。我想把这个字符串本地化。所以我的框架里有这样的东西:
public extension String {
public func localized(in bundle: Bundle) -> String {
if let path = bundle.path(forResource: Localize.currentLanguage(), ofType: "lproj"),
let bundle = Bundle(path: path) {
return bundle.localizedString(forKey: self, value: nil, table: nil)
}
return self
}
}
public extension Date {
public func timeAgo(format: DateUnitFormat = .short) -> String {
let thisFrameworkBundle = Bundle(for: Localize.self) // Class declared in the framework
//Whatever, just display a localized word
return "second".localized(in: thisFrameworkBundle)
}
}当我运行本地测试(框架本身内部的单元测试)时,本地化工作。找到了包裹。
但是当我从我的主应用程序调用timeAgo时,它就不再起作用了。
我试图将这行let thisFrameworkBundle = Bundle(for: Localize.self)转换为let thisFrameworkBundle = Bundle(identifier: "com.myIdentifier"),同样的事情(因此它在框架内工作,但当从主应用程序调用时就不能工作)。
编辑:
好的,我注意到Bundle(identifier: "com.myIdentifier")不能在框架内工作,因为我使用Cocoapods,它用cocoapod覆盖框架标识符。然而,我仍然不明白为什么使用Bundle(for: FrameworkClass.self)不能在主应用程序中工作(但是在框架的单元测试中工作)
发布于 2017-03-28 15:12:32
在这一刻,我可以给你两种方式。在过去的一年里,我一直在使用这个:
public func returnImage(_ named:String) -> UIImage {
let myBundle = Bundle.init(identifier: "com.[company].[framework]")
let imagePath = (myBundle?.path(forResource: "images", ofType: "bundle"))! + "/" + named
let theImage = UIImage(contentsOfFile: imagePath)
return theImage!
}键段将myBundle变量绑定到项目中定义的绑定ID。
我订阅了一个名为UseYourLoaf的博客。非常非常好的资源。如今,他们的帖子包含了一种完全不同的方法--使用类和bundleForClass。我只是发表了一条评论,询问我们两种方法的利弊。
我可以告诉您的是,如果您命名了一个BundleID,您可以使用我的例程访问资源。
https://stackoverflow.com/questions/43073096
复制相似问题