1. 程式人生 > >第三天:Swift利用CoreLocation獲取當前地址

第三天:Swift利用CoreLocation獲取當前地址

fun ons info 鏈接 sel ica with sources app

參考鏈接: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獲取當前地址