Home > Blockchain >  RealityKit – Cannot load ARView (found nil)
RealityKit – Cannot load ARView (found nil)

Time:05-30

I have ARView and Experience.rcproject file that I am trying to open in my VC, but problem is my screen black. Why?

import RealityKit
import UIKit
import ARKit

class ArVC: UIViewController, ARSCNViewDelegate {
    
    lazy var sceneView: ARSCNView = {
        let sceneView = ARSCNView()
        sceneView.delegate = self
        return sceneView
    }()
    
    var arView: ARView = {
        let arView = ARView()
        let boxAnchor = try! Experience.loadBox()
        arView.scene.anchors.append(boxAnchor)
        return arView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .clear
    }
    
    func createView() {
        self.view.addSubview(sceneView)
        self.view.addSubview(self.sceneView)
        self.sceneView.snp.makeConstraints { make in
            make.centerY.centerX.equalToSuperview()
        }
        
        view.subviews.forEach {
            $0.translatesAutoresizingMaskIntoConstraints = false
        }
        
        self.sceneView.addSubview(self.arView)
        self.arView.snp.makeConstraints { make in
            make.centerX.centerY.equalToSuperview()
        }
    }
}

What other options are there to set ARView programmatically? Thank you.

CodePudding user response:

This test code does the trick. If you're building AR project from scratch (by choosing simple iOS App template, not ARKit template), make sure you added Privacy - Camera Usage Description and Required device capabilities (Item 0 = ARKit) in info.plist file.

import RealityKit
import UIKit

class ViewController: UIViewController {
    
    var arView: ARView = {
        let arView = ARView(frame: .zero)
        let boxAnchor = try! Experience.loadBox()
        arView.scene.anchors.append(boxAnchor)
        return arView
    }()

    override func viewDidLoad() {
        super.viewDidLoad()
        self.view.backgroundColor = .red
        
        self.view.addSubview(self.arView)
            
        NSLayoutConstraint.activate([
            arView.topAnchor.constraint(equalTo: self.view.topAnchor),
            arView.leadingAnchor.constraint(equalTo: self.view.leadingAnchor),
            arView.bottomAnchor.constraint(equalTo: self.view.bottomAnchor),
            arView.trailingAnchor.constraint(equalTo: self.view.trailingAnchor)
        ])
        self.view.subviews.forEach {
            $0.translatesAutoresizingMaskIntoConstraints = false
        }
    }
}

Also I've noticed you added sceneView twice.

  • Related