I am building an app that will allow users to share their lists with each other. To do so, it will take a screenshot of the view and allow users to share that. When I go to share it, the app crashes. But when I go to save it to photos or files it works.
How can I fix this so users can share and save photos.
This is the code:
Button(action: {
self.isShareSheetPresented.toggle()
let image = theList.snapshot()
items.removeAll()
items.append(image)
}) {
Text("Share")
Image(systemName: "square.and.arrow.up")
}
}
.sheet(isPresented: $isShareSheetPresented) {
let image = theList.snapshot()
ShareSheetView(activityItems: items)
}
extension View {
func snapshot() -> UIImage {
let controller = UIHostingController(rootView: self)
let view = controller.view
let targetSize = controller.view.intrinsicContentSize
view?.bounds = CGRect(origin: .zero, size: targetSize)
view?.backgroundColor = .clear
let renderer = UIGraphicsImageRenderer(size: targetSize)
return renderer.image { _ in
view?.drawHierarchy(in: controller.view.bounds, afterScreenUpdates: true)
}
}
}
struct ShareSheetView: UIViewControllerRepresentable {
typealias Callback = (_ activityType: UIActivity.ActivityType?, _ completed: Bool, _ returnedItems: [Any]?, _ error: Error?) -> Void
let activityItems: [Any]
let applicationActivities: [UIActivity]? = nil
let excludedActivityTypes: [UIActivity.ActivityType]? = nil
let callback: Callback? = nil
func makeUIViewController(context: Context) -> UIActivityViewController {
let controller = UIActivityViewController(
activityItems: activityItems,
applicationActivities: applicationActivities)
controller.excludedActivityTypes = excludedActivityTypes
controller.completionWithItemsHandler = callback
return controller
}
func updateUIViewController(_ uiViewController: UIActivityViewController, context: Context) {
// nothing to do here
}
}