I have a widget bundle with a few different widgets. One of the widgets includes an image as a background -- the images are pulled from iCloud with a default image asset in the project in case the network call fails (and for the snapshot).
My issue is that I am using a submodule for the majority of my widget code. I would really like to keep the default image asset in the submodule instead of the main app. However, after creating an .xcassets folder in the submodule and putting the image there, the widget fails to recognize it. This widget is defined in the submodule with the new Assets folder.
I have verified the targets of the submodule's Assets are correct. I also attempted to deselect the Assets folder's target in the main app (which was the widget extension) but that had no effect. Perhaps, like an intents file, the assets need to be located in the parent app -- not a submodule. I don't know. Any ideas?
My widget bundle as defined in the main app:
import SwiftUI
import WidgetKit
import WidgetSubmodule
@main
struct MyAppsWidgets: WidgetBundle {
var body: some Widget {
Widget1()
Widget2()
Widget3()
}
}
Here is my widget TimelineEntry where I declare the image property:
public struct Widget3Entry: TimelineEntry {
public var date: Date
public var image: Image?
/// This method was added after my failed attempts to read the image from assets folder
private var defaultImage: Image {
let image = getDefaultImage()
return image
}
public init(date: Date, image: Image?) {
self.date = date
self.image = image ?? defaultImage
}
}
I thought that setting the image to Image("flower")
would pull the image from assets, but it does not. It does when the image is in the Assets folder in the main app, but not the submodule.
My embarrassing attempts at the getDefaultImage()
method seen above are partly as follows. I tried many things such as reading from a bundle and file manager, but to no avail.
func getDefaultImage() -> Image {
var itemToReturn: Image = Image("flower")
// let temppsoImg = PSOUniversalImage(byReferencing: URL(fileURLWithPath: path))
// let tempImage = Image("flower.jpg", bundle: Bundle.main)
// return tempImage
let fm = FileManager.default
let path = Bundle.main.resourcePath!
let items = try! fm.contentsOfDirectory(atPath: path)
for item in items {
if item.hasSuffix("jpg") {
itemToReturn = Image(item)
}
}
return itemToReturn
}
question from:
https://stackoverflow.com/questions/65623010/storing-widgetkit-image-assets-in-a-submodule-instead-of-main-app 与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…