无法使用 RealityKit 场景预览 SwiftUI Canvas

Can't preview SwiftUI Canvas with RealityKit scene

我只创建了一个新的 属性 RealityKit。 Xcode 将无法预览 SwiftUI canvas。 但是可以构建成功。

  1. 我通过 Xcode 创建应用程序。
  2. 选择增强现实应用程序并将用户界面设置为SwiftUI
  3. 项目可以正常运行。
import SwiftUI
import RealityKit

struct ContentView : View {
    var body: some View {
        return VStack {
            Text("123")
            ARViewContainer().edgesIgnoringSafeArea(.all)
        }
    }
}

struct ARViewContainer: UIViewRepresentable {

    func makeUIView(context: Context) -> ARView {

        let arView = ARView(frame: .zero)

        // Load the "Box" scene from the "Experience" Reality File
        let boxAnchor = try! Experience.loadBox()

        // Add the box anchor to the scene
        arView.scene.anchors.append(boxAnchor)

        return arView

    }

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

}

#if DEBUG
struct ContentView_Previews : PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}
#endif
  1. 我只在 makeUIView 函数中新建 属性 个 RealityKit。
let test: AnchoringComponent.Target.Alignment = .horizontal
  1. 项目无法预览canvas出现错误

    'Alignment' is not a member type of 'AnchoringComponent.Target'

  1. 项目仍然可以编译成功。

我很困惑我遇到了什么。 有人遇到同样的问题吗?

您必须解决几个问题:

  1. You can't use anchoring component in iOS Simulator or in SwiftUI Canvas Preview, because it can only be used for pinning a virtual content to the real world surfaces. So no simulator for AR apps.

RealityKit 锚点在 iOS 模拟器模式和 SwiftUI Canvas 预览模式下无用。

// Use it only for compiled AR app, not simulated...

let _: AnchoringComponent.Target.Alignment = .horizontal

不仅锚点在 iOS Simulator ModeSwiftUI Preview Mode 中没有用,而且其他 session-oriented 属性(包括 ARView.session)也像你一样可以在图片上看到:

  1. Change .backgroundColor in ARView to any other desirable one. Default color sometimes doesn't allow you to see a RealityKit scene. Looks like a bug.
func makeUIView(context: Context) -> ARView {

    let arView = ARView(frame: .zero)
    let boxAnchor = try! Experience.loadBox()
    boxAnchor.steelBox?.scale = SIMD3(5, 5, 5)
    boxAnchor.steelBox?.orientation = simd_quatf(angle: Float.pi/4, axis: SIMD3(1,1,0))

    arView.backgroundColor = .orange

    arView.scene.anchors.append(boxAnchor)
    return arView
}

下面是您现在可以在 SwiftUI 预览区看到的内容:

  1. And, of course, you have to give a Camera Permission before using AR app. And it doesn't matter what you're using: Storyboard or SwiftUI.

您需要在[=20中添加Camera Usage Description属性和arkit字符串=] 文件:

XML 版本如下所示:

/*  info.plist


<key>NSCameraUsageDescription</key>
    <string>Camera access for AR experience</string>

<key>UIRequiredDeviceCapabilities</key>
<array>
    <string>armv7</string>
    <string>arkit</string>
</array>

*/

解决这些问题后,应用程序按预期编译和工作(没有任何错误):