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.
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
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)
}
}
}
Post
Replies
Boosts
Views
Activity
I'm new to Xcode development so this question might be silly but when I create an iMessage project by selection "iMessage Application" template. And I want it to be standalone app for iMessage so that there is no iOS app as I don't see it useful in my case. I notice that there is only StoryBoard in the project and it looks a little bit different than iOS project. I watched Stanford iOS course 2020 so I'm use to SwiftUI and would prefer using it.