CoreLocation是??提供的一個定位框架。通過這個框架可以獲取 經緯度、海拔、指向、速度等信息。
CoreLocation
①
Info.plist
②
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
@IBOutlet weak var tableView: UITableView!
//定位管理者
let locationManager = CLLocationManager()
var myLocation:[String] = [] {
didSet {
tableView.reloadData()
}
}
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest //精度
locationManager.distanceFilter = 10 //更新距離
locationManager.requestAlwaysAuthorization() //發送授權申請
if CLLocationManager.locationServicesEnabled() {
//允許使用定位服務的話,開啟定位服務更新
locationManager.startUpdatingLocation()
print("定位開始")
}
tableView.delegate = self
tableView.dataSource = self
}
//定位改變執行,更新信息
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//獲取最新的坐標
guard let currLocation = locations.last else {
return print("沒有找到位置")
}
let label1 = "經度:\(currLocation.coordinate.longitude.keepTwo)"
let label2 = "緯度:\(currLocation.coordinate.latitude.keepTwo)"
let label3 = "海拔:\(currLocation.altitude.keepTwo)"
let label4 = "水平精度:\(currLocation.horizontalAccuracy.keepTwo)"
let label5 = "垂直精度:\(currLocation.verticalAccuracy.keepTwo)"
let label6 = "方向:\(currLocation.course)"
let label7 = "速度:\(currLocation.speed)"
myLocation = [label1,label2,label3,label4,label5,label6,label7]
}
}
extension ViewController: UITableViewDelegate,UITableViewDataSource {
func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return myLocation.count
}
func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCellWithIdentifier("myCell", forIndexPath: indexPath)
cell.textLabel?.text = myLocation[indexPath.row]
return cell
}
}
extension Double {
// 保留2位有效數字
var keepTwo:String {
return NSString(format: "%.2f", self) as String
}
}
/*
定位服務管理類CLLocationManager的desiredAccuracy屬性表示精準度,有如下6種選擇:
kCLLocationAccuracyBestForNavigation :精度最高,一般用于導航
kCLLocationAccuracyBest : 精確度最佳
kCLLocationAccuracyNearestTenMeters :精確度10m以內
kCLLocationAccuracyHundredMeters :精確度100m以內
kCLLocationAccuracyKilometer :精確度1000m以內
kCLLocationAccuracyThreeKilometers :精確度3000m以內
*/