iOS Developer首页投稿(暂停使用,暂停投稿)IOS

iOS开发 - 使用CoreLocation 定位

2016-07-15  本文已影响272人  小黑Swift

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以内
 */
上一篇 下一篇

猜你喜欢

热点阅读