gpt4 book ai didi

swift - 如何访问用户坐标

转载 作者:行者123 更新时间:2023-11-30 11:58:53 25 4
gpt4 key购买 nike

我正在尝试使用以下方式访问用户坐标:

import MapKit
import CoreLocation

override func viewDidLoad() {
super.viewDidLoad()
let locationManager = CLLocationManager()
let userCoordinates = (locationManager.location?.coordinate)!
}

但是,它在加载模拟器时崩溃。我将模拟器位置设置为 Apple,并将隐私 key 输入 info.plist,但我不确定为什么这没有获取用户位置。

最佳答案

在开始安全地使用设备当前的地理位置之前,您需要先做一些事情,并且根据您提供的代码,我假设您可能会丢失一些内容,因此这里是一个常见的设置,使用Google map ,其作用基本上与其他 map 一样:

class YourViewController: UIViewController, CLLocationManagerDelegate {

// properties
var locationManager = CLLocationManager()
var currentCoordinate: CLLocationCoordinate2D?

// load view
override func loadView() {
addLocationManager()
}

// add location manager
func addLocationManager() {

locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()

}

// location manager delegate: did change authorization
func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {

switch status {

case .restricted:
print("LOCATION ACCESS RESTRICTED")

case .denied:
print("LOCATION ACCESS DENIED")

case .notDetermined:
print("LOCATION ACCESS NOT DETERMINED")

case .authorizedAlways:
fallthrough

case .authorizedWhenInUse:
print("LOCATION STATUS GRANTED")

}

}


// location manager delegate: did fail with error
func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

locationManager.stopUpdatingLocation()
print("LOCATION ACCESS ERROR: \(error)")

}


// location manager delegate: did update locations
func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {

let lastLocation = locations.last!

// unhide map when current location is available
if mapView.isHidden {
mapView.camera = GMSCameraPosition.camera(withLatitude: lastLocation.coordinate.latitude, longitude: lastLocation.coordinate.longitude, zoom: 18, bearing: 0, viewingAngle: 0)
mapView.isHidden = false
}

// update current location properties
currentCoordinate = lastLocation.coordinate

}


}

如果您已导入 MapKit,则无需导入 CoreLocation

关于swift - 如何访问用户坐标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/47481289/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com