How to get Location user with CLLocationManager in swift?

前端 未结 7 2066
鱼传尺愫
鱼传尺愫 2020-11-29 04:49

I have this code on my view controller but this not working:

  import UIKit
  import CoreLocation

  class ViewController: UIViewController, CLLocationManag         


        
7条回答
  •  攒了一身酷
    2020-11-29 05:26

    Do following stuff in viewcontroller [Using swift] -

      class ViewController:     
      UIViewController,MKMapViewDelegate,CLLocationManagerDelegate {
    
    
      var locationManager: CLLocationManager?
      var usersCurrentLocation:CLLocationCoordinate2D?
    
      override func viewDidLoad() {
        super.viewDidLoad()
    
        self.locationManager = CLLocationManager()
    
        if CLLocationManager.authorizationStatus() == .NotDetermined{
            locationManager?.requestAlwaysAuthorization()
        }
    
        locationManager?.desiredAccuracy = kCLLocationAccuracyBest
        locationManager?.distanceFilter = 200
        locationManager?.delegate = self
        startUpdatingLocation()
    
        usersCurrentLocation = CLLocationCoordinate2DMake(LATTITUDE, LONGITUDE)
        let span = MKCoordinateSpanMake(0.005, 0.005)
        let region = MKCoordinateRegionMake(usersCurrentLocation!, span)
        mapview.setRegion(region, animated: true)
        mapview.delegate = self
        mapview.showsUserLocation = true
    
    }
    

    //MARK: CLLocationManagerDelegate methods

    func startUpdatingLocation() {
        self.locationManager?.startUpdatingLocation()
    }
    
    func stopUpdatingLocation() {
        self.locationManager?.stopUpdatingLocation()
    }
    

    // MARK: MKMapViewDelegate

    func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
        mapview.centerCoordinate = userLocation.location!.coordinate
        mapview.showsUserLocation = true
        regionWithGeofencing()
    
    }
    

提交回复
热议问题