CoreLocation使用步骤

来源:互联网 发布:淘宝代怎么刷大金额 编辑:程序博客网 时间:2024/06/05 02:47

使用swift描述

1.导入CoreLocation模块

import CoreLocation

2.设置CLLocationManager

var myLocationManager: CLLocationManager!
myLocationManager = CLLocationManager.init()myLocationManager.delegate = selfmyLocationManager.requestWhenInUseAuthorization() //请求使用位置信息,与info.plist配合,稍后会设置myLocationManager.desiredAccuracy = kCLLocationAccuracyBest //最佳精度myLocationManager.distanceFilter = 20 //位置更新的最小值,meter.myLocationManager.startUpdatingLocation() 

3.遵从CLLocationManagerDelegate协议

class ViewController: UIViewController, CLLocationManagerDelegate

4. 使定位服务可用

要使用位置信息, 需要进行如下的设置

设备:

  • 模拟器:

    • Product → Scheme → Edit Scheme, 或快捷键 ⌘-<
    • 勾选 Allow Location Simulation, 并设置默认位置

  • 真机
    • 打开 定位服务
    • 注意: 要把上面的Allow Location Simulation去掉,否则真机上也是用的模拟位置

代码

info.plist添加 NSLocationWhenInUseUsageDescription




上图中,”Use when in use“是在打开app时的一个弹框提示。
这个设置和上面代码中的 myLocationManager.requestWhenInUseAuthorization()要一起设置。使用时,iPhone会有如下弹框,点击Allow

上面的设置是在使用时使用位置信息,也可以按如下方法总是使用位置信息

  • info.plist
    • NSLocationAlwaysUsageDescription
  • code
    • myLocationManager.requestAlwaysAuthorization()

5.代理方法

5.1 位置更新

// MARK: CLLocationManagerDelegate methodsfunc locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {    for loc in locations {        print("\(loc.coordinate)")    }}

如果2中myLocationManager.distanceFilter = 20没有设置的话,这里就会不断输出:

CLLocationCoordinate2D(latitude: 22.284681, longitude: 114.158177)

每次执行myLocationManager.startUpdatingLocation()时,这里也会输出。

5.2 到新位置

func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {    let loc: CLLocationCoordinate2D = newLocation.coordinate    let longitude = loc.longitude    let latitude = loc.latitude    print("\(longitude), \(latitude)")}

这里发现一个问题:如果把5.1方法去掉,那么每次执行myLocationManager.startUpdatingLocation(),这里都会输出。但如果 5.1 和 5.2 同时保留的话,只会输出 5.1。

0 0