How to get the current location of iPhone through code?

后端 未结 7 1454
野的像风
野的像风 2020-12-30 16:53

How do you get the current location of iPhone through code? I need to track the location using GPS.

7条回答
  •  无人及你
    2020-12-30 17:35

    full code is here below

    1 drag map import framework give delegate

    in last line of this code self.yourmapreferencename.setRegion...

    // all code here

    import UIKit import MapKit import CoreLocation class ViewController: UIViewController, CLLocationManagerDelegate {

    @IBOutlet weak var mapView: MKMapView!
    var locationManager : CLLocationManager!
    
    override func viewDidLoad() {
        super.viewDidLoad()
    
        if CLLocationManager.locationServicesEnabled()
        {
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()
    
        }
    

    }

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation])
    {
    
        let location = locations.last! as CLLocation
        let center = CLLocationCoordinate2D(latitude: location.coordinate.latitude, longitude: location.coordinate.longitude)
        let region = MKCoordinateRegion(center: center, span: MKCoordinateSpan(latitudeDelta: 0.01, longitudeDelta: 0.01))
    
        self.mapView.setRegion(region, animated: true)
    }
    

    }

提交回复
热议问题