【问题标题】:How to get Location user with CLLocationManager in swift?如何在 swift 中使用 CLLocationManager 获取位置用户?
【发布时间】:2014-08-06 19:21:37
【问题描述】:

我的视图控制器上有这段代码,但这不起作用:

  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"
 }

我拥有在其他帖子中阅读的权限。但我没有得到 never,没有 println..

谢谢!!

【问题讨论】:

标签: ios swift core-location cllocationmanager


【解决方案1】:

以下是在 Swift 3 中获取用户位置的简单步骤

1) 首先在 plist 文件中添加这一行的描述

 NSLocationWhenInUseUsageDescription

2) 在您的项目中添加 CoreLocation.framework(在 Build Phases-> Link Binary With Library 部分下)

3) 在 AppDelegate 类中

   import CoreLocation

4) 创建locationManager对象如下

    var locationManager:CLLocationManager!

5) 在 didFinishLaunchingWithOptions 中编写如下代码

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

6) 如下所示确认 CLLocationManagerDelegate 委托

   class AppDelegate: UIResponder, UIApplicationDelegate, CLLocationManagerDelegate

7) 编写获取用户位置的 CLLocationManagerDelegate 委托方法

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)")
}

【讨论】:

    【解决方案2】:

    在视图控制器中执行以下操作 [使用 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 方法

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

    // 标记:MKMapViewDelegate

    func mapView(mapView: MKMapView, didUpdateUserLocation userLocation: MKUserLocation){
        mapview.centerCoordinate = userLocation.location!.coordinate
        mapview.showsUserLocation = true
        regionWithGeofencing()
    
    }
    

    【讨论】:

      【解决方案3】:

      应该写成 func locationManager(manager: CLLocationManager, didUpdateLocations 位置: [CLLocation]) {

      【讨论】:

        【解决方案4】:

        这与上面的代码相同,但在发布之日已清理以与 Swift 一起使用。这对我有用。

        向原海报致敬。

        (请注意,将其粘贴到您将用于处理位置信息的任何类中。)

        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)")
                    }
            }

        【讨论】:

        • 如何获取用户旧位置@Wade?​​span>
        • 我不确定您所说的旧位置是什么意思。你是说你上一次去过的地方吗?
        • - (void)locationManager:(CLLocationManager *)manager didUpdateToLocation:(CLLocation *)newLocation fromLocation:(CLLocation *)oldLocation 以上方法在Objective c中。我需要用相同的参数精确替换上述方法。
        【解决方案5】:

        首先在plist文件中添加这两行

        1) NSLocationWhenInUseUsageDescription

        2) NSLocationAlwaysUsageDescription

        那么这是类工作完成实现这个

        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)")
                }
        }
        }
        

        【讨论】:

        • 你好。我做了你写的一切,但 CLAuthorizationStatus.status 始终未确定。为什么?
        • 请检查您的设置 > yourapp > 位置权限
        • 'locationServicesEnabled' 不可用:从 iOS 7 及更早版本开始弃用的 API 在 Swift 中不可用
        • + 以 NSException 类型的未捕获异常终止。如何解决这个问题?
        • @jayeshkavathiya 为什么需要将代码放在 AppDelegate 类中?
        【解决方案6】:

        由于您将 location 声明为显式解包的可选项(CLLocationManager!),因此它需要一个初始化程序,或者在 jhurray 建议的 init 方法中,或者只是内联,如下所示:

        var location: CLLocationManager! = nil
        

        请注意,您还可能遇到其他问题,包括 iOS 8 对查询用户以获得使用 CoreLocation 的权限的新要求。请参阅此question 了解更多信息。

        【讨论】:

        • 我有权限,但我不知道我是否拥有所有权限。但我可以看到一个断点,它没有进入函数 func locationManager(location:CLLocationManager, didUpdateLocations locations:AnyObject []) { println("locations = (locations)") label1.text = "success" } 为什么我的应用不用这个功能??
        • 检查其他链接并确保您同时拨打requestWhenInUseAuthorization/requestAlwaysAuthorization 并在Info.plist 中设置正确的键。此外,请检查您是否拨打了正确的电话以启动经理。
        【解决方案7】:

        你需要有初始化函数。

        覆盖 init(coder:) 和 init(nibName: bundle:) 并添加您想要的任何自定义 init。

        因为您已经说过 location 不是可选的,所以您必须在您的 super init 调用所有 init 函数之前对其进行初始化。

        func init() {
        ...
        location = CLLocationManager()
        // either set delegate and other stuff here or in viewDidLoad
        super.init(nibName:nil, bundle:nil)
        // other initialization below
        
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 2017-07-03
          • 2016-02-25
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2019-09-02
          • 1970-01-01
          相关资源
          最近更新 更多