How to get Location user whith CLLocationManager i

2019-01-06 14:53发布

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

 import UIKit
 import CoreLocation
 class ViewController: UIViewController, CLLocationManagerDelegate {

  var location: CLLocationManager!

 override func viewDidLoad() {
    super.viewDidLoad()

    location=CLLocationManager()
    location.delegate = self
    location.desiredAccuracy=kCLLocationAccuracyBest
    location.startUpdatingLocation()
}

 func locationManager(location:CLLocationManager, didUpdateLocations locations:AnyObject[]) {
    println("locations = \(locations)")
    label1.text = "success"
}

I have the permisions how I read in other post. but I don't obtain never, no println..

Thanks!!

7条回答
我想做一个坏孩纸
2楼-- · 2019-01-06 15:43

Following are the simple steps for getting user location in Swift 3

1) First add this line in plist file with description

 NSLocationWhenInUseUsageDescription

2) Add CoreLocation.framework in your project(Under section Build Phases-> Link Binary With Library)

3) In AppDelegate class

   import CoreLocation

4) Create locationManager Object as follows

    var locationManager:CLLocationManager!

5) Write following code in didFinishLaunchingWithOptions

    locationManager = CLLocationManager()
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.distanceFilter = 200
    locationManager.requestWhenInUseAuthorization()
    locationManager.startUpdatingLocation()

6) Confirm CLLocationManagerDelegate delegate like as follows

   class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate

7) Write CLLocationManagerDelegate delegate method for getting user location

func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) {

    print("location error is = \(error.localizedDescription)")

}


func locationManager(_ manager: CLLocationManager,
                     didUpdateLocations locations: [CLLocation]) {

    let locValue:CLLocationCoordinate2D = (manager.location?.coordinate)!


    print("Current Locations = \(locValue.latitude) \(locValue.longitude)")
}
查看更多
登录 后发表回答