美文网首页
IOS8.0之后,9.0之前和IOS9.0之后获取后台定位定位方

IOS8.0之后,9.0之前和IOS9.0之后获取后台定位定位方

作者: Yumazhiyao | 来源:发表于2016-08-03 15:55 被阅读66次

方法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("-----")
    }
}
Snip20160803_5.png

方法二

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("-----")
    }
}
Snip20160803_5.png

另外设置

Snip20160803_6.png

相关文章

网友评论

      本文标题:IOS8.0之后,9.0之前和IOS9.0之后获取后台定位定位方

      本文链接:https://www.haomeiwen.com/subject/uliqsttx.html