Swift3.0 Day05 原生地图CoreLocation的使用

首先我们必须明确的一点是,我们在使用其他框架,不管是原生的还是第三方的,我们都需要导入库。然后我们才能进行之后的操作

导入CoreLocation##

选中项目,然后选择target中的Bulding Phases选择Link Binary With Libraries,点击加号,然后搜索CoreLocation即可

点击屏幕按钮实现CLLocationManagerDelegate###

  @IBAction func BtnClicked(_ sender: UIButton) {
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.requestAlwaysAuthorization()
        locationManager.startUpdatingLocation()
    }

CoreLOcation的代理方法

//定位失败的方法
  func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {
        
        self.locationLab.text = "Error while updating location " + error.localizedDescription
        
    }
    //更新定位的方法
    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
        CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
            
            if (error != nil) {
                self.locationLab.text = "Reverse geocoder failed with error" + error!.localizedDescription
                return
            }
            
            if placemarks!.count > 0 {
                let pm = placemarks![0]
                self.displayLocationInfo(placemark: pm)
            } else {
                self.locationLab.text = "Problem with the data received from geocoder"
            }
        })
    }
    
    func displayLocationInfo(placemark: CLPlacemark?) {
        if let containsPlacemark = placemark {
            //stop updating location to save battery life
            locationManager.stopUpdatingLocation()
            
            let locality = (containsPlacemark.locality != nil) ? containsPlacemark.locality : ""
            let postalCode = (containsPlacemark.postalCode != nil) ? containsPlacemark.postalCode : ""
            let administrativeArea = (containsPlacemark.administrativeArea != nil) ? containsPlacemark.administrativeArea : ""
            let country = (containsPlacemark.country != nil) ? containsPlacemark.country : ""
            
            self.locationLab.text = String.init(format: "\(locality)+\(postalCode)+\(administrativeArea!)+\(country!)")
        }
        
    }

最后选择在真机和数据流量的环境下测试,那样测试出来的数据会更加准确。
代码请戳原生地图CoreLocation的使用

你可能感兴趣的:(Swift3.0 Day05 原生地图CoreLocation的使用)