1、引用CoreLocation库
import CoreLocation
2、继承CLLocationManagerDelegate
class ViewController:UIViewController, CllocationManagerDelegate {
}
3、定义CLLocationManager对象
let locationManager:CLLocationManager = CLLocationManager()
3、启动定位服务
//设置定位服务管理器代理
locationManager.delegate = self
//设置定位精度
locationManager.desiredAccuracy = kCLLocationAccuracyBest
//更新距离
locationManager.distanceFilter = kCLDistanceFilterNone
//发送授权申请
locationManager.requestAlwaysAuthorization()
if CLLocationManager.locationServicesEnabled() {
//允许使用定位服务的话,开启定位服务更新
locationManager.requestAlwaysAuthorization()
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}
//定位错误
func locationManager(manager: CLLocationManager, didFailWithError error:NSError) {
}
//位置更新
func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {
//获取最新的坐标
let currLocation: CLLocation = newLocation
let 经度 = "\(currLocation.coordinate.longitude)"
let 纬度 = "\(currLocation.coordinate.latitude)"
let 海拔 = "\(currLocation.altitude)"
let 水平精度 = "\(currLocation.horizontalAccuracy)"
let 垂直精度 = "\(currLocation.verticalAccuracy)"
let 方向 = "\(currLocation.course)"
let 速度 = "\(currLocation.speed)"
}
//开始定位
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//获取最新坐标
let currLocation: CLLocation locations.last
//........
}