[Xcode10 实际操作]九、实用进阶-(10)定位设备的使用

本文将演示定位设备的使用。

在项目导航区,打开视图控制器的代码文件【ViewController.swift】

 1 import UIKit
 2 //导入需要用到的定位CoreLocation框架
 3 //该框架可以利用三种技术来实现定位:
 4 //1.全球卫星定位系统
 5 //2.蜂窝基站三角网定位
 6 //3.无线网络定位服务
 7 //其中,全球卫星定位系统是最精确的。
 8 import CoreLocation
 9 
10 //添加一个地理定位的代理协议CLLocationManagerDelegate
11 class ViewController: UIViewController, CLLocationManagerDelegate {
12 
13     //添加一个属性,该属性是框架提供的一个位置管理类
14     var locationManager:CLLocationManager!
15     override func viewDidLoad() {
16         super.viewDidLoad()
17         // Do any additional setup after loading the view, typically from a nib.
18         
19         //为了使用定位功能,需要创建一个位置管理器实例
20         locationManager = CLLocationManager()
21         //设置位置管理器的代理对象为当前视图控制器
22         locationManager.delegate = self
23         //给位置管理对象,设置最佳的精度级别
24         locationManager.desiredAccuracy = kCLLocationAccuracyBest
25         //设置在设备已经从上一次报告的位置,移动了1000米之后,再调用其委托方法
26         locationManager.distanceFilter = 1000.0
27         //开始启动位置管理器
28         locationManager.startUpdatingLocation()
29     }
30     
31     //添加一个代理方法,用来响应位置更新的事件。
32     func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
33         //获得定位设备返回的定位数组,并获得数组中的第一个元素
34         let location:CLLocation = locations[0]
35         //获得元素中的经度数值
36         let longitude = location.coordinate.longitude
37         //获得元素中的维度数值
38         let latitude = location.coordinate.latitude
39         //在控制台打印经度信息
40         print(longitude)
41         //在控制台打印维度信息
42         print(latitude)
43 
44         //系统定位服务是比较耗电的,当不使用定位服务时,
45         //需要及时停止定位服务的运行。
46         locationManager.stopUpdatingLocation()
47     }
48 
49     override func didReceiveMemoryWarning() {
50         super.didReceiveMemoryWarning()
51         // Dispose of any resources that can be recreated.
52     }
53 }

需要使用真实设备进行调试。

猜你喜欢

转载自www.cnblogs.com/strengthen/p/10088926.html