swift 定位 根据定位到的经纬度转换城市名
好久没写随笔了 最近这段时间项目有点紧 天天在加班 国庆 一天假都没放 我滴娃娃 好啦 牢骚就不发了 毕竟没有什么毛用 待我那天闲了专门写一篇吐槽的随笔 😁 😁 哇靠 接下来干正事
由于项目需要 所以需要定位到用户的城市 由于之前也没怎么搞过定位方面的东西 特此记一下 还挺简单的
(1)导入地图库 :MapKit.framework 就是这个
(2)在你需要用到的地方 import CoreLocation
(3)申请两个变量 记得遵守 CLLocationManagerDelegate 协议😁
var currLocation : CLLocation! //这个是保存定位信息的 别乱想哈
let locationManager : CLLocationManager = CLLocationManager()//这个也算是猪脚
(4)设置一些必要的属性 实现代理 开始定位
locationManager.requestAlwaysAuthorization()
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.distanceFilter = kCLLocationAccuracyKilometer
locationManager.delegate = self
locationManager.startUpdatingLocation()//开始定位 在定位完成后 会调用协议方法 这个就不用多说了
(5)接下来就是定位的协议方法了
//MARK:CLLocationManagerDelegate
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {//定位成功
currLocation = locations.last //取出经纬度
print(currLocation.coordinate.longitude)
print(currLocation.coordinate.latitude)
LonLatToCity()//去调用转换
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError) {//定位失败
print(error)
self.noticeOnlyText("哇靠!!定位怎么失败了呢")
}
(6)//这个就是要转换的方法了 😁
func LonLatToCity() {
let geocoder: CLGeocoder = CLGeocoder()
geocoder.reverseGeocodeLocation(currLocation) { (placemark, error) -> Void in
if(error == nil)//成功
{
let array = placemark! as NSArray
let mark = array.firstObject as! CLPlacemark
//这个是城市
let city: String = (mark.addressDictionary! as NSDictionary).valueForKey("City") as! String
//这个是国家
let country: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("Country") as! NSString
//这个是国家的编码
let CountryCode: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("CountryCode") as! NSString
//这是街道位置
let FormattedAddressLines: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("FormattedAddressLines")?.firstObject as! NSString
//这是具体位置
let Name: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("Name") as! NSString
//这是省
var State: String = (mark.addressDictionary! as NSDictionary).valueForKey("State") as! String
//这是区
let SubLocality: NSString = (mark.addressDictionary! as NSDictionary).valueForKey("SubLocality") as! NSString
//我在这里去掉了“省”和“市” 项目需求 可以忽略
State = State.stringByReplacingOccurrencesOfString("省", withString: "")
let citynameStr = city.stringByReplacingOccurrencesOfString("市", withString: "")
//在这里直接赋值给了之前定义的变量
self.provinces = State
self.city = citynameStr
print( State)
print( citynameStr)
//下面的这个方法只有我和上帝知道它是干嘛用的 😀
self.saveLocationSearch([State,citynameStr])
}
else
{
print(error)
self.noticeOnlyText("定位好像失败了哦")
}
}
}
(7)完活 😁