Skip to content

Instantly share code, notes, and snippets.

@MatthewWaller
Created January 27, 2022 04:35
Show Gist options
  • Star 3 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save MatthewWaller/37a3d889b684691c9f6a70d9abe76f92 to your computer and use it in GitHub Desktop.
Save MatthewWaller/37a3d889b684691c9f6a70d9abe76f92 to your computer and use it in GitHub Desktop.
Swift Playgrounds AR App Starter Code
import ARKit
import Combine
import RealityKit
import SwiftUI
@main
struct MyApp: App {
var body: some Scene {
WindowGroup {
ContentView()
}
}
}
struct ContentView: View {
var body: some View {
ARViewContainer()
}
}
struct ARViewContainer: UIViewRepresentable {
func makeUIView(context: Context) -> ARView {
let arView = context.coordinator.arView
let primeAnchor = context.coordinator.primeAnchor
arView.scene.anchors.append(primeAnchor)
return arView
}
func updateUIView(_ uiView: ARView, context: Context) {}
func makeCoordinator() -> Coordinator {
Coordinator(arView: ARView(frame: .zero),
primeAnchor: AnchorEntity(plane: .horizontal))
}
class Coordinator: NSObject, ARSessionDelegate {
var primeAnchor: AnchorEntity
var arView: ARView
var cancellables = Set<AnyCancellable>()
init(arView: ARView, primeAnchor: AnchorEntity) {
self.arView = arView
self.primeAnchor = primeAnchor
// Assuming you have a Star.reality file in your Resources area
let realityFile = Bundle.main.url(forResource: "Star", withExtension: "reality")!
super.init()
Entity.loadAnchorAsync(contentsOf: realityFile)
.sink(receiveCompletion: { (loadCompletion) in
if case let .failure(error) = loadCompletion {
print(error.localizedDescription)
}
}, receiveValue: { [weak self] (entity) in
self?.primeAnchor.addChild(entity)
}).store(in: &cancellables)
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment