首先,您必须检查ARGeoTrackingConfiguration
您的设备是否支持:
import ARKit
@main class AppDelegate: UIResponder, UIApplicationDelegate {
var window: UIWindow?
func application(_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions:
[UIApplication.LaunchOptionsKey: Any]?) -> Bool {
if !ARGeoTrackingConfiguration.isSupported {
let sb = UIStoryboard(name: "Main", bundle: nil)
window?.rootViewController = sb.instantiateViewController(withIdentifier:
"unsupportedConfiguration")
}
return true
}
}
...然后检查您所在位置是否可以使用地理跟踪:
ARGeoTrackingConfiguration.checkAvailability { (available, error) in
if !available {
let errorDescription = error?.localizedDescription ?? ""
let recommendation = "You need a place where geo tracking is supported."
let restart = UIAlertAction(title: "Restart", style: .default) { (_) in
self.restartSession()
}
self.alertUser(withTitle: "Geo tracking unavailable",
message: "\(errorDescription)\n\(recommendation)",
actions: [restart])
}
}
之后提供Info.plist
相机和位置许可。以下是有关位置服务授权请求的综合信息,其中包括:
- NSLocationWhenInUseUsageDescription
- NSLocationAlwaysAndWhenInUseUsageDescription
- NSLocationUsageDescription
- NSLocationAlwaysUsageDescription
现在只支持美国城市和英国首都......
支持 ARGeoTrackingConfiguration 的城市列表。
然后您必须运行地理配置:
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
let config = ARGeoTrackingConfiguration()
sceneView.session.run(config)
}
然后将参数化锚点添加到会话中:
@IBOutlet var sceneView: ARSCNView!
override func viewDidLoad() {
super.viewDidLoad()
sceneView.delegate = self
sceneView.scene = SCNScene()
let coordinate = CLLocationCoordinate2D(latitude: 40.730610,
longitude: -73.935242)
let geoAnchor = ARGeoAnchor(name: "Geo Anchor",
coordinate: coordinate,
altitude: 33.0)
sceneView.session.add(anchor: geoAnchor)
}
之后,您可以在 ARGeoAnchor 的帮助下添加模型:
extension ViewController: ARSCNViewDelegate {
func renderer(_ renderer: SCNSceneRenderer,
didAdd node: SCNNode,
for anchor: ARAnchor) {
guard let geoAnchor = anchor as? ARGeoAnchor,
geoAnchor.name == "Geo Anchor"
else { return }
print(geoAnchor.coordinate)
let boxGeometry = SCNBox(width: 1.0,
height: 1.0,
length: 1.0,
chamferRadius: 0.1)
boxGeometry.firstMaterial?.diffuse.contents = UIColor.red
let cube = SCNNode(geometry: boxGeometry)
node.addChildNode(cube)
}
}