(转载于http://www.hangge.com/blog/cache/detail_784.html)
CoreLocation这个定位框架除了可以获取设备的位置数据,还可以获取设备的方向(可以用来实现指南针功能等)。
1,CLHeading对象通过一组属性提供航向相关数据:
magneticHeading :磁极方向(磁北对应于随时间变化的地球磁场极点)
trueHeading :真实方向(真北始终指向地理北极点)
headingAccuracy :方向的精度
timestamp :Core Loaction确定位置时的时间戳
description : 方向数据
2,方向值的含义
不管是磁极方向还是真实方向,值的单位是度,类型为CLLocationDirection,即双精度浮点数。
0.0 :前进方向为北
90.0 :前进方向为东
180.0 :前进方向为南
270.0 :前进方向为西
3,下面通过样例进行演示
![原文:Swift - 使用CoreLocation获取设备方向(真实方向,磁极方向)](http://www.hangge.com/blog_uploads/201507/2015070713483042905.png)
1 import UIKit 2 3 import CoreLocation 4 5 6 7 class ViewController: UIViewController, CLLocationManagerDelegate { 8 9 10 11 //定位管理器 12 13 let locationManager:CLLocationManager = CLLocationManager() 14 15 16 17 @IBOutlet weak var label1: UILabel! 18 19 @IBOutlet weak var label2: UILabel! 20 21 @IBOutlet weak var label3: UILabel! 22 23 @IBOutlet weak var label4: UILabel! 24 25 26 27 override func viewDidLoad() { 28 29 super.viewDidLoad() 30 31 32 33 //设置定位服务管理器代理 34 35 locationManager.delegate = self 36 37 //设置定位进度 38 39 locationManager.desiredAccuracy = kCLLocationAccuracyBest 40 41 //发送授权申请 42 43 locationManager.requestAlwaysAuthorization() 44 45 } 46 47 48 49 //获取设备是否允许使用定位服务 50 51 func locationManager(manager: CLLocationManager!, 52 53 didChangeAuthorizationStatus status: CLAuthorizationStatus) { 54 55 if status == CLAuthorizationStatus.NotDetermined || status == CLAuthorizationStatus.Denied{ 56 57 58 59 }else{ 60 61 //允许使用定位服务的话,开启定位服务更新 62 63 locationManager.startUpdatingHeading() 64 65 println("方向定位开始") 66 67 68 69 //关闭定位 70 71 //locationManager.stopUpdatingHeading() 72 73 } 74 75 } 76 77 78 79 //方向改变执行 80 81 func locationManager(manager: CLLocationManager!, didUpdateHeading newHeading: CLHeading!) { 82 83 label1.text = "磁极方向:\(newHeading.magneticHeading)" 84 85 label2.text = "真实方向:\(newHeading.trueHeading)" 86 87 label3.text = "方向的精度:\(newHeading.headingAccuracy)" 88 89 label4.text = "时间:\(newHeading.timestamp)" 90 91 } 92 93 }