首先在info.plist里增加两行:NSLocationAlwaysUsageDescription和NSLocationWhenInUseUsageDescription,如下图中倒数3和4行
然后
import CoreLocation
给类增加代理:
CLLocationManagerDelegate
//用于定位服务管理类,它能够给我们提供位置信息和高度信息,也可以监控设备进入或离开某个区域,还可以获得设备的运行方向
var locationManager : CLLocationManager!
var currLocation : CLLocation!
主要代码,总共三个函数:
var locationManager : CLLocationManager! var currLocation : CLLocation! override func viewDidLoad() { //初始化位置管理器 locationManager = CLLocationManager() locationManager.delegate = self //设备使用电池供电时最高的精度 locationManager.desiredAccuracy = kCLLocationAccuracyBest //精确到1000米,距离过滤器,定义了设备移动后获得位置信息的最小距离 locationManager.distanceFilter = kCLLocationAccuracyKilometer if ios8() { //如果是IOS8及以上版本需调用这个方法 locationManager.requestAlwaysAuthorization() //使用应用程序期间允许访问位置数据 locationManager.requestWhenInUseAuthorization(); //启动定位 locationManager.startUpdatingLocation() } } //FIXME: CoreLocationManagerDelegate 中获取到位置信息的处理函数 func locationManager(manager: CLLocationManager,didUpdateLocations locations: [CLLocation]) { let location:CLLocation = locations[locations.count-1] as CLLocation currLocation=location if (location.horizontalAccuracy > 0) { self.locationManager.stopUpdatingLocation() print("wgs84坐标系 纬度: \(location.coordinate.latitude) 经度: \(location.coordinate.longitude)") self.locationManager.stopUpdatingLocation() print("结束定位") } //使用坐标,获取地址 let geocoder = CLGeocoder() var p:CLPlacemark? geocoder.reverseGeocodeLocation(currLocation,completionHandler: { (placemarks,error) -> Void in if error != nil { print("获取地址失败: \(error!.localizedDescription)") return } let pm = placemarks! as [CLPlacemark] if (pm.count > 0){ p = placemarks![0] as CLPlacemark print("地址:\(p?.name!)") }else{ print("没地址!") } }) } //FIXME: 获取位置信息失败 func locationManager(manager: CLLocationManager,didFailWithError error: NSError) { print(error) }
判断手机系统版本:
func ios8() -> Bool { var versionCode:String = UIDevice.currentDevice().systemVersion let version = NSString(string: versionCode).doubleValue return version >= 8.0 }原文链接:https://www.f2er.com/swift/325249.html