You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

代码创建的ARSCNView无法正常工作:黑屏且未请求相机权限

解决ARSCNView黑屏且不触发相机权限请求的问题

你遇到的核心问题是没有启动AR会话:ARSCNView只是承载AR内容的视图容器,要让它调用相机并显示画面,必须手动配置并运行ARSession。之前的代码仅把视图添加到屏幕上,但未触发相机访问逻辑,所以系统不会弹出权限请求,视图默认显示黑屏。

解决步骤

  1. 在视图生命周期中管理AR会话
    建议在viewWillAppear中启动会话(适配视图可见时的资源加载时机),同时在viewWillDisappear中暂停会话,避免后台持续占用相机资源。
  2. 配置对应AR会话配置类
    根据场景需求选择ARWorldTrackingConfiguration(通用AR场景)、ARFaceTrackingConfiguration等合适的配置。

修改后的完整代码

import ARKit

class ViewController: UIViewController {
    let sceneView = ARSCNView()

    override func viewDidLoad() {
        super.viewDidLoad()
        // 用AutoLayout适配所有屏幕尺寸(比直接设置frame更可靠)
        sceneView.translatesAutoresizingMaskIntoConstraints = false
        view.addSubview(sceneView)
        
        NSLayoutConstraint.activate([
            sceneView.topAnchor.constraint(equalTo: view.topAnchor),
            sceneView.leadingAnchor.constraint(equalTo: view.leadingAnchor),
            sceneView.trailingAnchor.constraint(equalTo: view.trailingAnchor),
            sceneView.bottomAnchor.constraint(equalTo: view.bottomAnchor)
        ])
        
        // 可选:设置代理监听会话状态(如错误、跟踪状态变化)
        sceneView.delegate = self
    }
    
    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)
        
        // 创建AR世界追踪配置
        let configuration = ARWorldTrackingConfiguration()
        // 启动会话,这一步会触发相机权限请求
        sceneView.session.run(configuration)
    }
    
    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)
        
        // 暂停会话,释放相机资源
        sceneView.session.pause()
    }
}

// 可选实现ARSCNViewDelegate处理会话事件
extension ViewController: ARSCNViewDelegate {
    func session(_ session: ARSession, didFailWithError error: Error) {
        print("AR会话错误: \(error.localizedDescription)")
    }
    
    func sessionWasInterrupted(_ session: ARSession) {
        print("AR会话被中断")
    }
}

额外注意事项

  • 确认Info.plist中的NSCameraUsageDescription(对应显示名称“Privacy - Camera Usage Description”)已填写明确的权限说明文本,比如“需要访问相机以提供AR体验”,否则系统可能拒绝权限请求。
  • 不要在viewDidLoad中直接启动会话,此时视图可能未完全显示,也无法处理视图消失时的资源释放逻辑。

内容的提问来源于stack exchange,提问作者Tony

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.12 15:25:06