I'm trying to take a screenshot of WebView. I have successfully done it when I'm displaying it on the screen but the goal is to not need this but just take the screenshot. Right now this code just gives white even though Text component is working correctly. I believe it could be something with website not having time to load but I'm not sure what is the solution.
Other
Code Block swift import SwiftUI import CoreData extension View { func takeScreenshotView(rect: CGRect) -> UIImage { let window = UIWindow(frame: rect) let hosting = UIHostingController(rootView: self) window.rootViewController = hosting window.makeKeyAndVisible() return hosting.view.setImage(rect: rect) } } struct ContentView: View { @State var image: UIImage? var body: some View { VStack { Button("Snap") { print("take screenshot") image = WebView(url: "https://lankinen.xyz").takeScreenshotView(rect: CGRect(x: 0, y: 0, width: 100, height: 100)) // image = Text("hello world").takeScreenshotView(rect: CGRect(x: 0, y: 0, width: 100, height: 100)) } if image != nil { Image(uiImage: image!) } } .padding() .background(Color.green) } }
Other
Code Block swift import Foundation import SwiftUI import WebKit struct WebView: UIViewRepresentable { var url: String func makeUIView(context: Context) -> some UIView { guard let url = URL(string: self.url) else { return WKWebView() } let request = URLRequest(url: url) let wkWebView = WKWebView() wkWebView.load(request) return wkWebView } func updateUIView(_ uiView: UIViewType, context: Context) {} } extension UIView { func setImage(rect: CGRect) -> UIImage { let renderer = UIGraphicsImageRenderer(bounds: rect) return renderer.image { rendererContext in layer.render(in: rendererContext.cgContext) } } }