Created
January 27, 2022 04:35
-
-
Save MatthewWaller/37a3d889b684691c9f6a70d9abe76f92 to your computer and use it in GitHub Desktop.
Swift Playgrounds AR App Starter Code
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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