第三天:Swift利用CoreLocation获取当前地址
Posted CHM
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了第三天:Swift利用CoreLocation获取当前地址相关的知识,希望对你有一定的参考价值。
参考链接:https://www.jianshu.com/p/ade69f95bffc
1 import UIKit 2 import CoreLocation 3 4 class ViewController: UIViewController, CLLocationManagerDelegate { 5 6 @IBOutlet weak var showLocationBtn: UIButton! 7 @IBOutlet weak var locationLabel: UILabel! 8 9 var locationManager: CLLocationManager! 10 11 override func viewDidLoad() { 12 super.viewDidLoad() 13 // Do any additional setup after loading the view, typically from a nib. 14 15 UIApplication.shared.statusBarStyle = .lightContent 16 17 } 18 19 @IBAction func showLocationAction(_ sender: UIButton) { 20 21 locationManager = CLLocationManager() 22 locationManager.delegate = self 23 24 locationManager.desiredAccuracy = kCLLocationAccuracyBest 25 locationManager.requestAlwaysAuthorization() 26 locationManager.startUpdatingLocation() 27 } 28 29 override func didReceiveMemoryWarning() { 30 super.didReceiveMemoryWarning() 31 // Dispose of any resources that can be recreated. 32 } 33 34 } 35 36 extension ViewController { 37 func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { 38 self.locationLabel.text = "Error while updating location: " + error.localizedDescription 39 } 40 41 func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 42 CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: { 43 (placemarks, error) -> Void in 44 45 if error != nil { 46 self.locationLabel.text = "Reverse geocoder failed with error:" + error!.localizedDescription 47 return 48 } 49 50 if placemarks!.count > 0 { 51 let pm = placemarks![0] 52 self.displayLocationInfo(pm) 53 } else { 54 self.locationLabel.text = "Error existed in the data received from geocoder" 55 } 56 }) 57 } 58 59 func displayLocationInfo(_ placemark: CLPlacemark?) { 60 guard let containsPlacemark = placemark else {return} 61 62 locationManager.stopUpdatingLocation() 63 64 let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : "" 65 let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : "" 66 let adminstrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : "" 67 let country = (containsPlacemark.country != nil) ? containsPlacemark.country : "" 68 69 self.locationLabel.text = postalCode! + " " + locality! 70 self.locationLabel.text?.append("\\n") 71 self.locationLabel.text?.append(adminstrativeArea! + ", " + country!) 72 } 73 }
以上是关于第三天:Swift利用CoreLocation获取当前地址的主要内容,如果未能解决你的问题,请参考以下文章
不请求访问 coreLocation 的权限并在 swift 中崩溃
iOS项目开发实战——使用CoreLocation获取当前位置信息
如何使用 coreLocation (iOS/Swift) 读取完整地址