2

我正在尝试使用 SwiftUI、RealityKit 和 ARKit 在脸上加载不同的模型。

struct AugmentedRealityView: UIViewRepresentable {

    @Binding var modelName: String

    func makeUIView(context: Context) -> ARView {
    
        let arView = ARView(frame: .zero)
    
        let configuration = ARFaceTrackingConfiguration()

        arView.session.run(configuration, options: [.removeExistingAnchors, 
                                                    .resetTracking])
    
        loadModel(name: modelName, arView: arView)
    
        return arView
    
    }

    func updateUIView(_ uiView: ARView, context: Context) { }

    private func loadModel(name: String, arView: ARView) {

        var cancellable: AnyCancellable? = nil
    
        cancellable = ModelEntity.loadAsync(named: name).sink(
                 receiveCompletion: { loadCompletion in
            
            if case let .failure(error) = loadCompletion {
                print("Unable to load model: \(error.localizedDescription)")
            }                
            cancellable?.cancel()
        },
        receiveValue: { model in
            
            let faceAnchor = AnchorEntity(.face)
            arView.scene.addAnchor(faceAnchor)
            
            faceAnchor.addChild(model)
            
            model.scale = [1, 1, 1]
        })
    }
}

这就是我加载它们的方式,但是当相机视图打开并加载一个模型时,其他模型将不会被加载。有人可以帮我吗?

4

1 回答 1

0

当您的值Binding发生更改时,SwiftUI 正在调用您的updateUIView(_:,context:)实现,这并没有说明。

此外,您没有存储AnyCancellable. 当返回的令牌sink被释放时,请求将被取消。在尝试加载更大的模型时,这可能会导致意外失败。

要解决这两个问题,请使用Coordinator.

import UIKit
import RealityKit
import SwiftUI
import Combine
import ARKit

struct AugmentedRealityView: UIViewRepresentable {
    class Coordinator {
        private var token: AnyCancellable?
        private var currentModelName: String?
        
        fileprivate func loadModel(_ name: String, into arView: ARView) {
            // Only load model if the name is different from the previous one
            guard name != currentModelName else {
                return
            }
            currentModelName = name
            
            // This is optional
            // When the token gets overwritten
            // the request gets cancelled
            // automatically
            token?.cancel()
            
            token = ModelEntity.loadAsync(named: name).sink(
                receiveCompletion: { loadCompletion in
                    
                    if case let .failure(error) = loadCompletion {
                        print("Unable to load model: \(error.localizedDescription)")
                    }
                },
                receiveValue: { model in
                    
                    let faceAnchor = AnchorEntity(.camera)
                    arView.scene.addAnchor(faceAnchor)
                    
                    faceAnchor.addChild(model)
                    
                    model.scale = [1, 1, 1]
                })
            }
        
        fileprivate func cancelRequest() {
            token?.cancel()
        }
    }
    
    @Binding var modelName: String
    
    func makeCoordinator() -> Coordinator {
        Coordinator()
    }
    
    static func dismantleUIView(_ uiView: ARView, coordinator: Coordinator) {
        coordinator.cancelRequest()
    }
    
    func makeUIView(context: Context) -> ARView {
        
        let arView = ARView(frame: .zero)
        
        let configuration = ARFaceTrackingConfiguration()
        
        arView.session.run(configuration, options: [.removeExistingAnchors,
                                                    .resetTracking])
        
        context.coordinator.loadModel(modelName, into: arView)
        
        return arView
        
    }
    
    func updateUIView(_ uiView: ARView, context: Context) {
        context.coordinator.loadModel(modelName, into: uiView)
    }
}

我们创建一个嵌套Coordinator类来保存AnyCancellable令牌并将loadModel函数移动到Coordinator. 除了 SwiftUI 之外View,它还Coordinator存在于class您的视图可见的情况下(请始终记住,SwiftUI 可能会随意创建和销毁您View,它的生命周期与屏幕上显示的实际“视图”无关)。

在 outloadModel类中,我们仔细检查我们的值是否Binding实际发生了变化,这样当 SwiftUI 更新我们的 时,我们不会取消对同一模型的持续请求View,例如因为环境的变化。

然后我们实现该makeCoordinator函数来构造我们的Coordinator对象之一。在 inmakeUIView和 inupdateUIView我们调用我们的loadModel函数Coordinator

dimantleUIView方法是可选的。当Coordinatorget 被解构时,我们token的也会被释放,这将触发 Combine 取消正在进行的请求。

于 2020-08-19T14:42:08.743 回答