My app is currently structured to use dynamic library to enable code reuse. I have images stored within my dynamic library so they can easily be shared between different app targets. This works fine in iOS because I can use the UIImage(named:, in:, compatibleWith:)
initializer to load the image from my dynamic library. However, this initializer doesn't seem to be available on watchOS. Is there any other method of loading images from a dynamic library (with a different bundle) on watchOS. By the way, the image is stored within an Asset Catalog.
Loading a UIImage in WatchKit from a different Bundle
295 views Asked by Harish At
2
There are 2 answers
0
On
I'm sharing a piece of code that will load image from bundle and it is compatible with OSX, watchOS and iOS. if you only want the solution for watchOS only then take #elseif os(watchOS)
part out
#if os(OSX)
import AppKit
public typealias Image = NSImage
#elseif os(watchOS)
import WatchKit
public typealias Image = UIImage
#else
import UIKit
public typealias Image = UIImage
#endif
public extension String
{
func image(in bundle: Bundle? = Bundle.main) -> Image?
{
#if os(OSX)
guard let img = bundle?.image(forResource: self) else {
return nil
}
#elseif os(watchOS)
guard let resource = bundle?.resourceURL, let img = try? Image(data: Data(contentsOf: resource)) else {
return nil
}
#else
guard let img = Image(named: self, in: bundle, compatibleWith: nil) else {
return nil
}
#endif
return img
}
}
The workaround I discovered was to use the
Bundle
'sresourceURL
to get the root directory of theBundle
's resource folder and then loading the images manually from the filesystem usingData(contentsOf:)
andUIImage(data:)
. This does not seem to work with Asset Catalogs though.