在Swift中实现CLLocationManagerDelegate方法

时间:2014-06-05 02:25:20

标签: cllocationmanager swift ios8

我一直试图让它工作一段时间,我来这里问 - 如何在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会抛出编译器错误。有什么想法吗?

5 个答案:

答案 0 :(得分:57)

如果您还没有将NSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescription键添加到您的plist,它们现在已成为必填项,


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

  • 即使应用未打开并正在使用,也请将NSLocationAlwaysUsageDescription用于要使用设备位置的应用。

  • 仅在应用程序处于打开和使用状态时,才能将NSLocationWhenInUseUsageDescription用于要使用设备位置的应用。

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

设置任一字符串会在安装/首次使用时提示弹出:"允许" ThisApp"即使您不使用应用程序即可访问您的位置。

这是 plist 文件的屏幕

enter image description here

答案 1 :(得分:6)

首先在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)")
        }
}

答案 2 :(得分:4)

获取用户当前位置: -

第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步:       不要忘记在Info.plist中添加NSLocationAlwaysUsageDescription,因为在iOS 8中必须添加它。这将要求允许使用用户的位置。

答案 3 :(得分:3)

我有同样的问题。 didUpdateLocations - 无效。运行你的应用程序 转到“设置”页面 - >隐私 - >位置和关闭位置服务。 didFailWithError将捕获有关缺少位置服务的错误。然后打开它。从那时起,didUpdateLocations将捕获位置。

答案 4 :(得分: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]

时未调用委托