Canvatorium Visio Lab 5030
Adding a WebKit web view in SwiftUI.
I used this lab to learn how to add a web view in SwiftUI. I positioned this view in an immersive space and attached it to a parent 3D box that can be moved around the scene.
This lab was some early prototype work for a new project I’m considering.
This article was helpful to understand the process of using the web view in SwiftUI.
struct Lab5030: View {
var body: some View {
RealityView { content, attachments in
let model = ModelEntity(
mesh: .generateBox(width: 0.2, height: 0.03, depth: 0.03),
materials: [SimpleMaterial(color: .black, isMetallic: false)])
model.position = SIMD3(x: 0, y: 1, z: -1.4)
model.components.set(InputTargetComponent())
model.components.set(CollisionComponent(shapes: [.generateBox(width: 0.2, height: 0.03, depth: 0.03)]))
model.components.set(HoverEffectComponent())
content.add(model)
if let attachmentEntity = attachments.entity(for: "card01") {
content.add(attachmentEntity)
model.addChild(attachmentEntity, preservingWorldTransform: true)
attachmentEntity.setPosition([0, 0.4, 0], relativeTo: model)
attachmentEntity.setScale(SIMD3(x: 1, y: 1, z: 1), relativeTo: model)
}
} update: { content, attachments in
} attachments: {
Attachment(id: "card01") {
WebView(url: URL(string: "https://vrhermit.com/")!)
.frame(width: 1600, height: 900)
}
}
.gesture(dragGesture)
}
var dragGesture: some Gesture {
DragGesture()
.targetedToAnyEntity()
.onChanged { value in
let newPostion = value.convert(value.location3D, from: .local, to: value.entity.parent!)
value.entity.position = newPostion
}
.onEnded { value in
print(value.entity)
}
}
}
// Credit: https://sarunw.com/posts/swiftui-webview/
struct WebView: UIViewRepresentable {
let url: URL
func makeUIView(context: Context) -> WKWebView {
return WKWebView()
}
func updateUIView(_ webView: WKWebView, context: Context) {
let request = URLRequest(url: url)
webView.load(request)
}
}