Swift 2 – Can't get user location with CLLocationManager

前端 未结 3 920
难免孤独
难免孤独 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:48

    Try getting the location by getting the last object for the array locations in the method locationManager(_:,didUpdateLocations locations: [CLLocations]) .

    Something like this:

    func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            let locValue:CLLocationCoordinate2D = locations.last!
            print("locations = \(locValue.latitude) \(locValue.longitude)")
    }  
    
    0 讨论(0)
  • 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

    0 讨论(0)
  • 2020-12-11 23:13

    you have to use these location access permission in your plist.

    1. NSLocationAlwaysAndWhenInUseUsageDescription
    2. NSLocationWhenInUseUsageDescription

    you are not using always and in InUse permiossion

    Note by Apple:

    This app has attempted to access privacy-sensitive data without a usage description. The app's Info.plist must contain both NSLocationAlwaysAndWhenInUseUsageDescription and NSLocationWhenInUseUsageDescription keys with string values explaining to the user how the app uses this data

    0 讨论(0)
提交回复
热议问题