很多的APP中都会用到用户的当前位置信息,本文将实现这个小功能
import UIKit
import CoreLocation //添加引用
class ViewController: UIViewController,CLLocationManagerDelegate {
let locationManager:CLLocationManager = CLLocationManager() //实例化一个CLLocationManager对象
override func viewDidLoad() {
super.viewDidLoad()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest //设置为最高的精度
if(ios8()){
locationManager.requestAlwaysAuthorization() //如果是IOS8及以上版本需调用这个方法
}
locationManager.startUpdatingLocation() //start updating location
}
func ios8() -> Bool {
var versionCode:String = UIDevice.currentDevice().systemVersion
let start:String.Index = advance(versionCode.startIndex, 0)
let end:String.Index = advance(versionCode.startIndex, 1)
let range = Range<String.Index>(start: start, end: end)
let version = NSString(string: UIDevice.currentDevice().systemVersion.substringWithRange(range)).doubleValue
return version >= 8.0
}
//重写这个方法获取位置
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!){
let location:CLLocation = locations[locations.count - 1] as! CLLocation //得到数组中的最后一个元素
if location.horizontalAccuracy > 0 {
let latitude = location.coordinate.latitude //得到经伟度
let longtitude = location.coordinate.longitude
locationManager.stopUpdatingLocation() //stop updating location
}
}
//重写当发生错误时要调用的方法
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!){
println(error)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
}
}
写要上面的代码还需要在info.plist文件内添加以下几个键值:
请求获得应用一直使用定位服务授权:NSLocationAlwaysUsageDescription:“Please allow me to get you location”
在用户第一交使用APP时也会询问是否允许APP获取当前用户的地理位置信息
请求获得应用使用时的定位服务授权:Location Usage Description:“我们需要使用你的地理位置储备“
iOS 8 还提供了更加人性化的定位服务选项。App 的定位服务不再仅仅是关闭或打开,现在,定位服务的启用提供了三个选项,「永不」「使用应用程序期间」和「始终」。同时,考虑到能耗问题,如果一款 App 要求始终能在后台开启定位服务,iOS 8 不仅会在首次打开 App 时主动向你询问,还会在日常使用中弹窗提醒你该 App 一直在后台使用定位服务,并询问你是否继续允许。在iOS7及以前的版本,如果在应用程序中使用定位服务只要在程序中调用startUpdatingLocation方法应用就会询问用户是否允许此应用是否允许使用定位服务,同时在提示过程中可以通过在info.plist中配置通过配置Privacy - Location Usage Description告诉用户使用的目的,同时这个配置是可选的。
但是在iOS8中配置配置项发生了变化,可以通过配置NSLocationAlwaysUsageDescription或者NSLocationWhenInUseUsageDescription来告诉用户使用定位服务的目的,并且注意这个配置是必须的,如果不进行配置则默认情况下应用无法使用定位服务,打开应用不会给出打开定位服务的提示,除非安装后自己设置此应用的定位服务。同时,在应用程序中需要根据配置对requestAlwaysAuthorization或locationServicesEnabled方法进行请求。