如何通过按钮开启/关闭ARKit?附实现代码求优化建议
Hey there! Let's work through this to get a cleaner, more reliable ARKit toggle for your button. First, let's quickly note the issues with your current approaches:
- Your first
arSwitch()function has a couple of problems: the case labels have inconsistent capitalization (btnPressedvsbtnpressed), and it's hardcoding boolean values instead of toggling the current state. That won't work for a proper on/off switch. - The second approach is closer, but
sceneView.scene.stop()isn't a valid method—SCNScene doesn't have astop()function. To control ARKit, you need to interact with the ARSession rather than just the scene.
Here's a more robust, Apple-recommended implementation that handles state properly and uses ARKit's native APIs:
// Connect these outlets to your storyboard elements @IBOutlet weak var arToggleSwitch: UISwitch! @IBOutlet weak var sceneView: ARSCNView! // Store your AR and non-AR scenes (adjust the non-AR one to fit your needs) private let arScene = ARSCNScene() private let staticScene = SCNScene(named: "StaticScene.scn")! // Or use an empty scene if needed // Track the current state of the AR session to avoid mismatches private var isARSessionActive = false @IBAction func arButtonTapped(_ sender: Any) { // Toggle the active state first isARSessionActive = !isARSessionActive arToggleSwitch.isOn = isARSessionActive if isARSessionActive { // Start the AR session with a standard tracking configuration let arConfig = ARWorldTrackingConfiguration() sceneView.session.run(arConfig) // Switch to the AR scene and enable AR-specific UI sceneView.scene = arScene sceneView.showsStatistics = true // Optional: Show FPS/tracking info } else { // Pause the AR session to stop tracking and save resources sceneView.session.pause() // Switch back to your non-AR scene and disable AR UI sceneView.scene = staticScene sceneView.showsStatistics = false } }
Why this works better:
- State consistency: We use a dedicated
isARSessionActivevariable to keep track of whether AR is running, so the switch and actual session state never get out of sync. - Proper ARSession control: Apple recommends using
session.run()andsession.pause()to manage ARKit's lifecycle—this stops camera capture and motion tracking when paused, which saves battery and processing power. - Clear scene separation: It explicitly swaps between your AR and non-AR scenes, making the logic easy to follow and extend later.
A few extra tips:
- If you don't need a separate non-AR scene, you can just pause the session and leave the current scene (but the camera feed will freeze).
- Always pause the AR session when your view disappears (add
sceneView.session.pause()toviewWillDisappear) to prevent background resource usage. - Make sure you've requested camera permissions in your
Info.plist(addNSCameraUsageDescription)—ARKit won't run without user approval.
内容的提问来源于stack exchange,提问作者jon
相关产品推荐
相关产品推荐

