方法1,代码设置
import UIKit
//1,导入CoreLocation
import CoreLocation
class ViewController: UIViewController {
//2,懒加载CLLocationManager
lazy var locationM : CLLocationManager = {
let locationM = CLLocationManager()
//3,设置代理
locationM.delegate = self
return locationM
}()
override func viewDidLoad() {
super.viewDidLoad()
//发送请求,调用该方法,只在App进入前台时候进行定位,并且需要在info.plist中加上NSLocationWhenInUseUsageDescription这个键,值随便填
if #available(iOS 8.0, *) {//版本设置
locationM.requestWhenInUseAuthorization()
}
//6,启动定位
locationM.startUpdatingLocation()
}
}
//遵守协议
extension ViewController : CLLocationManagerDelegate {
//4,实现代理方法
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
print("-----")
}
}
方法二
import UIKit
//1,导入CoreLocation
import CoreLocation
class ViewController: UIViewController {
//2,懒加载CLLocationManager
lazy var locationM : CLLocationManager = {
let locationM = CLLocationManager()
//3,设置代理
locationM.delegate = self
return locationM
}()
override func viewDidLoad() {
super.viewDidLoad()
//发送请求,调用该方法,只在App进入前台时候进行定位,并且需要在info.plist中加上NSLocationWhenInUseUsageDescription这个键,值随便填
if #available(iOS 8.0, *) {
locationM.requestWhenInUseAuthorization()
if #available(iOS 9.0, *) {
//IOS9.0之后必须设置该属性为true,才能在Xcode里设置后台运行之后后台定位
locationM.allowsBackgroundLocationUpdates = true
}
}
//6,启动定位
locationM.startUpdatingLocation()
}
}
//遵守协议
extension ViewController : CLLocationManagerDelegate {
//4,实现代理方法
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
print(locations)
print("-----")
}
}
另外设置