swift 定位

时间:2024-01-19 18:35:27
iOS 8 及以上需要在info.plist文件中添加下面两个属性
  NSLocationWhenInUseUsageDescription 使用应用期间
  NSLocationAlwaysUsageDescription 始终
swift 定位
swift 定位
swift 定位
import UIKit

import CoreLocation //系统定位包

class ViewController: UIViewController,CLLocationManagerDelegate {

    override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib. getCurrentLocation()
} override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
// Dispose of any resources that can be recreated.
} //CodeStart /// 定位对象
let locationManager = CLLocationManager() /// 当前所在城市(默认空)
var currentCity = "" /**
定位获取所在城市
*/
func getCurrentLocation(){ locationManager.desiredAccuracy = kCLLocationAccuracyBest locationManager.delegate = self if(UIDevice.currentDevice().systemVersion>="8.0"){ //locationManager.requestAlwaysAuthorization() locationManager.requestWhenInUseAuthorization() } locationManager.startUpdatingLocation()
} /**
定位失败
*/
func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
println(error.code)
} /**
定位完成调用
*/
func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) { let cloc = locations.last as! CLLocation let geoCoder = CLGeocoder() var error = NSError() geoCoder.reverseGeocodeLocation(cloc, completionHandler: { (placeMarks:[AnyObject]!, error:NSError!) -> Void in
if error == nil { var placeMark: AnyObject = placeMarks[0] var locationInfo:Dictionary = placeMark.addressDictionary var locationCity = locationInfo["State"] as! String if self.currentCity != locationCity{ self.currentCity = locationCity println("当前定位城市:\(self.currentCity)") } } }) manager.stopUpdatingLocation() } }