Swift 2 – Can't get user location with CLLocationManager

前端 未结 3 955
难免孤独
难免孤独 2020-12-11 22:29

Here is my VC code:

import UIKit
import MapKit
import CoreLocation

class ViewController: UIViewController, MKMapViewDelegate, CLLocationMan         


        
3条回答
  •  不知归路
    2020-12-11 22:50

    This works for me

    Swift 2 - (Xcode 7.2.1)

    ViewController.swift

    
    import UIKit
    import CoreLocation
    
    class ViewController: UIViewController, CLLocationManagerDelegate {
    
        var locationManager: CLLocationManager = CLLocationManager()
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.delegate = self
            locationManager.requestWhenInUseAuthorization()
            locationManager.startUpdatingLocation()
        }
    
        func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
    
            self.locationManager.stopUpdatingLocation()
    
            let latestLocation = locations.last
    
            let latitude = String(format: "%.4f", latestLocation!.coordinate.latitude)
            let longitude = String(format: "%.4f", latestLocation!.coordinate.longitude)
    
            print("Latitude: \(latitude)")
            print("Longitude: \(longitude)")
        }
    }
    

    info.plist

    Add a new line

    Information Property List: NSLocationWhenInUseUsageDescription

    Type: String

    Value: The application uses this information to show you your location

提交回复
热议问题