【问题标题】:Implement CLLocationManagerDelegate methods in Swift在 Swift 中实现 CLLocationManagerDelegate 方法
【发布时间】:2014-06-05 02:25:20
【问题描述】:

我一直试图让它工作一段时间,我来这里是想问 - 我如何在 Swift 中使用 CLLocationManagerDelegate 方法?我把它放在班级的首位:

var locationManager = CLLocationManager()

我已将以下内容放入我的 viewDidLoad 方法中:

locationManager.delegate = self
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.startUpdatingLocation()

我已经尝试使用这些委托方法但无济于事:

func locationManager(manager: CLLocationManager!, didUpdateLocations locations: AnyObject[]!) {
    locationReceived = true
}

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) {
    locationReceived = false
}

我也尝试过在函数前面使用@optional,但是 Xcode 会引发编译器错误。有什么想法吗?

【问题讨论】:

  • 您的代码似乎对我有用,您是否收到对话框询问您的应用是否可以使用您的位置?
  • @voidref 既然你提到了它,我就没有得到对话框。这有点奇怪......我刚刚检查了设置,并且该应用也获得了位置访问权限。

标签: cllocationmanager swift ios8


【解决方案1】:

您需要将NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription 键添加到您的plist(如果您还没有),它们现在是强制性的,


iOS8+ 需要将这两个字符串之一设置为使用位置。您使用哪一个取决于您打算如何询问位置。

  • NSLocationAlwaysUsageDescription 用于希望使用设备位置的应用程序,即使应用程序未打开且未使用。

  • NSLocationWhenInUseUsageDescription 用于仅在应用打开和使用时才想使用设备位置的应用。

注意:添加字符串时,在构建和运行之前,请从您的设备上删除应用程序并让它重新安装。似乎如果该应用程序在您升级到 iOS8 之前被授权使用位置,它不会再次请求您的许可,也不会看到您设置了这些字符串。执行删除和全新安装可以解决此问题。

设置任一字符串都会在安装/首次使用时弹出如下提示:“即使您不使用该应用程序,也允许“ThisApp”访问您的位置”

这是 plist 文件的屏幕截图

【讨论】:

  • You mean like this?这也没有使对话框出现。
  • 不,显然 iOS8 需要设置另外两个字符串之一(请参阅我的编辑)。您使用哪一个应该取决于您打算如何根据我的理解询问位置,但我找不到任何更具体的信息。为了全面披露,即使添加了所示的字符串,我仍然没有让我的工作(我的问题似乎出在其他地方,我目前正试图让我的运行没有 swift),我只想提一下字符串,因为现在必填。
  • 另外,当您添加字符串时,在构建和运行之前,请从您的设备上删除应用程序并让它重新安装。似乎如果该应用程序在您升级到 iOS8 之前被授权使用位置,它不会再次请求您的许可,也不会看到您设置了这些字符串。进行删除和全新安装为我解决了它,终于又可以工作了!
  • 将此添加到 info.plist NSLocationUsageDescription您的消息NSLocationAlwaysUsageDescription您的消息NSLocationWhenInUsageDescription你的消息
  • info.plist 键是: NSLocationAlwaysUsageDescription 和 NSLocationWhenInUseUsageDescription ... 正确拼写会有所不同。这记录在 CLLocationManager 文档中 - 搜索此文本。在我纠正这个问题后,我的应用程序工作了 - 在调用程序时请求许可。
【解决方案2】:

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

1) NSLocationWhenInUseUsageDescription

2) NSLocationAlwaysUsageDescription

import CoreLocation

class ViewController: UIViewController, CLLocationManagerDelegate

var seenError : Bool = false
var locationFixAchieved : Bool = false
var locationStatus : NSString = "Not Started"

var locationManager: CLLocationManager!

override func viewDidLoad() {
    super.viewDidLoad()
}

  func initLocationManager() {
   seenError = false
   locationFixAchieved = false
    locationManager = CLLocationManager()
   locationManager.delegate = self
   locationManager.locationServicesEnabled
   locationManager.desiredAccuracy = kCLLocationAccuracyBest
    locationManager.requestAlwaysAuthorization()
}

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

【讨论】:

    【解决方案3】:

    获取用户当前位置:-

    第 1 步: let locationManager = CLLocationManager() // make object of CLLocationManager class.

    第 2 步: In viewDidLoad instantiate the CLLocationManager class like,

    // 用于后台

    self.locationManager.requestAlwaysAuthorization()
    
    // For use in foreground
    
    self.locationManager.requestWhenInUseAuthorization()
    
    if (CLLocationManager.locationServicesEnabled())
    {
    locationManager.delegate = self
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters
    locationManager.startUpdatingLocation()
    }
    

    第三步:现在实现CLLocationManager的委托方法

      func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {
    
        var locValue:CLLocationCoordinate2D = manager.location.coordinate
    
        println("locations = \(locValue.latitude) \(locValue.longitude)")
    
      }
    

    第 4 步: 不要忘记在 Info.plist 中添加NSLocationAlwaysUsageDescription,因为在 iOS 8 中必须添加它。这将请求使用用户位置的权限。

    【讨论】:

      【解决方案4】:

      我有同样的问题。 didUpdateLocations - 没有工作。运行您的应用程序。 转到设置页面 -> 隐私 -> 位置并关闭定位服务。 didFailWithError 将捕获有关缺少位置服务的错误。然后打开它。从那一刻起,didUpdateLocations 将捕获位置。

      【讨论】:

      • 这似乎工作了一次,但是当我从 Xcode 重新启动应用程序时,我又回到没有得到任何位置更新。
      • 是的,我知道。但我想这是 XCode 6 的问题。让我们等待 beta 2 :)
      【解决方案5】:

      这是一个有点旧的线程,但上述方法都不适用于 Swift 2.2 xCode 7.3.1。

      问题是我正在使用:

      func locationManager(manager: CLLocationManager!, didUpdateLocation locations: [AnyObject]!) {
          print("Got location")
          locationManager.stopUpdatingLocation()
      }
      

      这从未被调用过。当我改为:

      func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
          print("Got location")
          locationManager.stopUpdatingLocation()
      }
      

      一切顺利。似乎使用 [AnyObject] 时未调用委托

      【讨论】:

        猜你喜欢
        • 2014-12-13
        • 1970-01-01
        • 1970-01-01
        • 2015-01-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多