I want to add a widget to my app that will display the # of pickups the user has for the day. I have the DeviceActivityReport working in the main app but can't get it to display in the widget since it is not a supported view for widgets. Is there any workaround for getting this view to the widget?
I tried converting the DeviceActivityReport view to a UI image thinking maybe that would be a way to use a widget approved view type but ImageRenderer seems to fail to render an image for the view (which is just a Text view).
To summarize my questions:
- Is it possible to display a DeviceActivityReport in a widget? If so, what is the best practice?
- Is converting the DeviceActivityReport view into an image and displaying that in a widget an option?
Here's my attempt to convert the DeviceActivityReport view into a UIImage:
import SwiftUI
import _DeviceActivity_SwiftUI
struct PickupsDeviceActivityReport: View {
@State private var context: DeviceActivityReport.Context = .totalActivity
@State private var renderedImage = Image(systemName: "exclamationmark.triangle")
@Environment(\.displayScale) var displayScale
var body: some View {
renderedImage
.onAppear { render() }
.onChange(of: context) {
_ in render()
}
}
@MainActor func render() {
let renderer = ImageRenderer(content: DeviceActivityReport(context))
renderer.scale = displayScale
if let uiImage = renderer.uiImage {
renderedImage = Image(uiImage: uiImage)
}
}
}
Help is appreciated. Thank you.