iOS Swift 4 集成 GPS 定位功能

GPS 返回的位置信息包含了经纬度、高度等信息,在 Swift 中可以实时获取用户手机的 GPS 定位,不过在实现上略为繁琐。

本文从一个空白 ViewController 开始,介绍如何在 iOS Swift 中集成 GPS 定位功能。

创建项目

在 Xcode 中创建一个 iOS 项目,初始时会给出一个空白的 ViewController,代码如下:

import UIKit

class ViewController: UIViewController {

override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

}

在代码中集成 GPS 功能

首先需要导入相关库:

import LocalAuthentication
import CoreLocation

接着需要将 CLLocationManagerDelegate 添加进 ViewController 的继承对象中:

class ViewController: UIViewController, CLLocationManagerDelegate {

在类中定义变量:

var locationManager: CLLocationManager = CLLocationManager()
var cntLocation: CLLocation!

viewDidLoad() 中添加对应的初始化代码,主要包括设置精度、请求权限、开始记录信息等:

override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
cntLocation = nil
}

添加函数 locationManager,当位置信息发生更新时,该函数会被自动调用,所有的历史定位信息作为参数 locations 传进来:

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if (locations.count == 0) { return }
let cntLocation = locations[locations.count - 1]
print("latitude: \(cntLocation.coordinate.latitude), longitude: \(cntLocation.coordinate.longitude)")
}

全部代码如下:

import UIKit
import LocalAuthentication
import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate {
var locationManager: CLLocationManager = CLLocationManager()

override func viewDidLoad() {
super.viewDidLoad()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.delegate = self
locationManager.requestWhenInUseAuthorization()
locationManager.startUpdatingLocation()
}

override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if (locations.count == 0) { return }
let cntLocation = locations[locations.count - 1]
print("latitude: \(cntLocation.coordinate.latitude), longitude: \(cntLocation.coordinate.longitude)")
}
}

修改 Info.plist

最后一步,由于位置信息涉及用户的隐私,我们还需要在项目中的 Info.plist 文件中添加一项 Privacy - Location When In Use Usage Description,在后面的 Value 项中填入 App 请求位置信息的理由(任意字符串皆可,用户将会看到)。

启动!

编译、运行,在 Xcode 的控制台输出中就可以看到 GPS 定位的实时输出了:

latitude: 37.332595519999984, longitude: -122.03031801999995
latitude: 37.33241210544181, longitude: -122.03050892969908
latitude: 37.332409011234624, longitude: -122.03048799764015
latitude: 37.33240735611452, longitude: -122.03047659100626

注意这不是每隔固定时间更新的,而是当位置信息发生变化时才会更新。