How to get Location user with CLLocationManager in swift?

前端 未结 7 2067
鱼传尺愫
鱼传尺愫 2020-11-29 04:49

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

  import UIKit
  import CoreLocation

  class ViewController: UIViewController, CLLocationManag         


        
相关标签:
7条回答
  • 2020-11-29 05:15

    You need to have init functions.

    Override init(coder:) and init(nibName: bundle:) and add any custom init you want.

    Because you have said that location is not optional, you must initialize it before your super init calls in ALL of your init functions.

    func init() {
    ...
    location = CLLocationManager()
    // either set delegate and other stuff here or in viewDidLoad
    super.init(nibName:nil, bundle:nil)
    // other initialization below
    
    }
    
    0 讨论(0)
  • 2020-11-29 05:17

    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)")
    }
    
    0 讨论(0)
  • 2020-11-29 05:24

    Since you're declaring location as an explicitly unwrapped optional (CLLocationManager!) it requires an initializer, either in an init method as suggested by jhurray, or just inline, as:

    var location: CLLocationManager! = nil
    

    Note that you've got other possible problems as well, including that iOS 8 has new requirements for querying the user for permission to use CoreLocation. See this question for more information.

    0 讨论(0)
  • 2020-11-29 05:25

    This is the same code as above but cleaned up to work with Swift as of the date of this posting. This worked for me.

    Kudos to the original poster.

    (note, stick this into whatever class you will use to handle your location stuff.)

    var lastLocation = CLLocation()
    var locationAuthorizationStatus:CLAuthorizationStatus!
    var window: UIWindow?
    var locationManager: CLLocationManager!
    var seenError : Bool = false
    var locationFixAchieved : Bool = false
    var locationStatus : NSString = "Not Started"
    
    override func viewDidAppear(animated: Bool) {
        super.viewDidAppear(animated)
        
        
        self.initLocationManager()
        
    }
        // Location Manager helper stuff
        func initLocationManager() {
            seenError = false
            locationFixAchieved = false
            locationManager = CLLocationManager()
            locationManager.delegate = self
            locationManager.desiredAccuracy = kCLLocationAccuracyBest
            
            locationManager.requestAlwaysAuthorization()
        }
        
        // Location Manager Delegate stuff
        
        func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
            locationManager.stopUpdatingLocation()
            if ((error) != nil) {
                if (seenError == false) {
                    seenError = true
                    print(error)
                }
            }
        }
        
        func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
            if (locationFixAchieved == false) {
                locationFixAchieved = true
                var locationArray = locations as NSArray
                var locationObj = locationArray.lastObject as CLLocation
                var coord = locationObj.coordinate
                
                println(coord.latitude)
                println(coord.longitude)
            }
        }
        
        func locationManager(manager: CLLocationManager!,  didChangeAuthorizationStatus status: CLAuthorizationStatus) {
                var shouldIAllow = false
                
                switch status {
                case CLAuthorizationStatus.Restricted:
                    locationStatus = "Restricted Access to location"
                case CLAuthorizationStatus.Denied:
                    locationStatus = "User denied access to location"
                case CLAuthorizationStatus.NotDetermined:
                    locationStatus = "Status not determined"
                default:
                    locationStatus = "Allowed to location Access"
                    shouldIAllow = true
                }
                NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
                if (shouldIAllow == true) {
                    NSLog("Location to Allowed")
                    // Start location services
                    locationManager.startUpdatingLocation()
                } else {
                    NSLog("Denied access: \(locationStatus)")
                }
        }

    0 讨论(0)
  • 2020-11-29 05:26

    Do following stuff in viewcontroller [Using swift] -

      class ViewController:     
      UIViewController,MKMapViewDelegate,CLLocationManagerDelegate {
    
    
      var locationManager: CLLocationManager?
      var usersCurrentLocation:CLLocationCoordinate2D?
    
      override func viewDidLoad() {
        super.viewDidLoad()
    
        self.locationManager = CLLocationManager()
    
        if CLLocationManager.authorizationStatus() == .NotDetermined{
            locationManager?.requestAlwaysAuthorization()
        }
    
        locationManager?.desiredAccuracy = kCLLocationAccuracyBest
        locationManager?.distanceFilter = 200
        locationManager?.delegate = self
        startUpdatingLocation()
    
        usersCurrentLocation = CLLocationCoordinate2DMake(LATTITUDE, LONGITUDE)
        let span = MKCoordinateSpanMake(0.005, 0.005)
        let region = MKCoordinateRegionMake(usersCurrentLocation!, span)
        mapview.setRegion(region, animated: true)
        mapview.delegate = self
        mapview.showsUserLocation = true
    
    }
    

    //MARK: CLLocationManagerDelegate methods

    func startUpdatingLocation() {
        self.locationManager?.startUpdatingLocation()
    }
    
    func stopUpdatingLocation() {
        self.locationManager?.stopUpdatingLocation()
    }
    

    // MARK: MKMapViewDelegate

    func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
        mapview.centerCoordinate = userLocation.location!.coordinate
        mapview.showsUserLocation = true
        regionWithGeofencing()
    
    }
    
    0 讨论(0)
  • 2020-11-29 05:28

    first add this two line in plist file

    1) NSLocationWhenInUseUsageDescription

    2) NSLocationAlwaysUsageDescription

    Then this is class working complete implement this

    import UIKit 
    import CoreLocation
    
    @UIApplicationMain
    
    class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate {
    
    var window: UIWindow?
    var locationManager: CLLocationManager!
    var seenError : Bool = false
    var locationFixAchieved : Bool = false
    var locationStatus : NSString = "Not Started"
    
    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: NSDictionary?) -> Bool {
        initLocationManager();
        return true
    }
    
    // Location Manager helper stuff
    func initLocationManager() {
        seenError = false
        locationFixAchieved = false
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.locationServicesEnabled
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
    
        locationManager.requestAlwaysAuthorization()
    }
    
    // Location Manager Delegate stuff
    
    func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
        locationManager.stopUpdatingLocation()
        if (error) {
            if (seenError == false) {
                seenError = true
               print(error)
            }
        }
    }
    
    func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
        if (locationFixAchieved == false) {
            locationFixAchieved = true
            var locationArray = locations as NSArray
            var locationObj = locationArray.lastObject as CLLocation
            var coord = locationObj.coordinate
    
            println(coord.latitude)
            println(coord.longitude)
        }
    }
    
    func locationManager(manager: CLLocationManager!,
        didChangeAuthorizationStatus status: CLAuthorizationStatus) {
            var shouldIAllow = false
    
            switch status {
            case CLAuthorizationStatus.Restricted:
                locationStatus = "Restricted Access to location"
            case CLAuthorizationStatus.Denied:
                locationStatus = "User denied access to location"
            case CLAuthorizationStatus.NotDetermined:
                locationStatus = "Status not determined"
            default:
                locationStatus = "Allowed to location Access"
                shouldIAllow = true
            }
            NSNotificationCenter.defaultCenter().postNotificationName("LabelHasbeenUpdated", object: nil)
            if (shouldIAllow == true) {
                NSLog("Location to Allowed")
                // Start location services
                locationManager.startUpdatingLocation()
            } else {
                NSLog("Denied access: \(locationStatus)")
            }
    }
    }
    
    0 讨论(0)
提交回复
热议问题