Swift 使用CoreLocation獲取定位與位置資訊
阿新 • • 發佈:2019-02-03
大多數情況下APP會在開啟應用的時候獲取當前的位置,所以我寫在APPDelegate裡
第一步
import CoreLocation
var locationManager = CLLocationManager()
第二步func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
//開啟定位
loadLocation()
return true
}
第三步 實現代理方法extension AppDelegate: CLLocationManagerDelegate
{
//開啟定位
func loadLocation()
{
locationManager.delegate = self
//定位方式
locationManager.desiredAccuracy = kCLLocationAccuracyBest
//iOS8.0以上才可以使用
if(UIDevice.currentDevice().systemVersion >= "8.0"){
//始終允許訪問位置資訊
locationManager.requestAlwaysAuthorization()
//使用應用程式期間允許訪問位置資料
locationManager.requestWhenInUseAuthorization()
}
//開啟定位
locationManager.startUpdatingLocation()
}
//獲取定位資訊
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
//取得locations陣列的最後一個
let location:CLLocation = locations[locations.count -1]
currLocation = locations.last!
//判斷是否為空
if(location.horizontalAccuracy > 0){
lat = Double(String(format: "%.1f", location.coordinate.latitude))
long = Double(String(format: "%.1f", location.coordinate.longitude))
print("緯度:\(long!)")
print("經度:\(lat!)")
LonLatToCity()
//停止定位
locationManager.stopUpdatingLocation()
}
}
//出現錯誤
func locationManager(manager: CLLocationManager, didFinishDeferredUpdatesWithError error: NSError?) {
print(error)
}
///將經緯度轉換為城市名
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
//城市
var 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: "")
}
else
{
print(error)
}
}
}
}