27

I've been trying to get this to work for awhile now, and I've come here to ask- how do I go about with using the CLLocationManagerDelegate methods in Swift? I've put this at the top of my class:

var locationManager = CLLocationManager()

I've put the following into my viewDidLoad method:

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

And I've tried using these delegate methods with no avail:

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

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

I've also tried using @optional in front of the functions, but Xcode then throws a compiler error. Any ideas?

4

5 回答 5

58

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


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

  • 用于想要使用NSLocationAlwaysUsageDescription设备位置的应用程序,即使应用程序未打开且正在使用。

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

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

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

这是plist文件屏幕截图。

在此处输入图像描述

于 2014-06-05T09:41:57.930 回答
7

首先在 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)")
        }
}
于 2014-07-11T12:20:23.937 回答
5

获取用户当前位置:-

步骤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()
}

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

  func locationManager(manager: CLLocationManager!, didUpdateLocations locations: [AnyObject]!) {

    var locValue:CLLocationCoordinate2D = manager.location.coordinate

    println("locations = \(locValue.latitude) \(locValue.longitude)")

  }

第 4 步: 不要忘记添加NSLocationAlwaysUsageDescriptionInfo.plist,因为在 iOS 8 中是强制添加的。这将请求使用用户位置的权限。

于 2014-09-06T10:51:35.143 回答
3

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

于 2014-06-06T18:15:49.357 回答
0

这是一个有点老的线程,但上述方法都不适用于 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] 时未调用委托

于 2016-09-10T10:20:41.613 回答