首先你必须检查是否ARGeoTrackingConfiguration
您的设备支持。
要求:您需要配备 A12+ 芯片并支持蜂窝 (GPS) 的设备。
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
with camera and 位置权限。这里有一个全面的信息定位服务授权请求 https://developer.apple.com/documentation/corelocation/requesting_authorization_for_location_services包括:
- NSLocationWhenInUseUsageDescription
- NSLocationAlwaysAndWhenInUseUsageDescription
- NSLocationUsageDescription
- NSLocationAlwaysUsageDescription
目前仅支持美国、英国、澳大利亚、加拿大、日本和新加坡的几个城市......
支持 ARGeoTrackingConfiguration 的城市列表 https://developer.apple.com/documentation/arkit/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)
}
}
P.S.
如果您对 ARCore 中类似功能的工作原理感兴趣,请阅读我的文章地理空间API https://stackoverflow.com/questions/50382855/arcore-and-sceneform-with-geolocation/72213814#72213814.