CLLocation Manager in Swift to get Location of User

后端 未结 13 2097
不知归路
不知归路 2020-11-27 04:48

I am trying to convert an old app in ObjC to Swift as a practice exercise and have ran in to some issues. The way I had it in the old app, it was establishing the CLLocatio

13条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2020-11-27 05:15

    Here is my very simple code that works:

    first add Core Location framework in General/Linked Frameworks and Libraries

    then add following into Info.plist:

    NSLocationWhenInUseUsageDescription
    blablabla
    NSLocationAlwaysUsageDescription
    blablabla
    

    this is my ViewController.swift file:

    import UIKit
    import CoreLocation
    
    class ViewController: UIViewController, CLLocationManagerDelegate {
    
        var locationManager:CLLocationManager!
    
        override func viewDidLoad() {
            super.viewDidLoad()
    
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            locationManager.requestAlwaysAuthorization()
            locationManager.startUpdatingLocation()
        }
    
    
        func locationManager(manager:CLLocationManager, didUpdateLocations locations: [CLLocation]) {
            print("locations = \(locations)")
        }
    
    }
    

提交回复
热议问题