iOS開發 - 使用CoreLocation 定位

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以內
 */
最后編輯于
?著作權歸作者所有,轉載或內容合作請聯系作者
平臺聲明:文章內容(如有圖片或視頻亦包括在內)由作者上傳并發布,文章內容僅代表作者本人觀點,簡書系信息發布平臺,僅提供信息存儲服務。

推薦閱讀更多精彩內容