CLLocationManagerDelegate未接收更新

时间:2016-02-06 16:10:47

标签: swift uiviewcontroller swift2 core-location

我有一个视图控制器,它具有以下功能:

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

    print("loc")
}
func locationManager(manager: CLLocationManager, didFailWithError error: NSError){
    if(error.code == CLError.Denied.rawValue){
        print("error")
    }
}

这是该班的直接孩子:

import UIKit
import CoreLocation

class UIViewLocationManager : UIViewController, CLLocationManagerDelegate{

    func locationManager(manager: CLLocationManager, didChangeAuthorizationStatus status: CLAuthorizationStatus) {
        print(status.rawValue)
        switch status {
        case .NotDetermined:
            break

        case .AuthorizedWhenInUse:
            if #available(iOS 9.0, *) {
                manager.requestLocation()
            } else {
                manager.startUpdatingLocation()
            }
            break

        case .AuthorizedAlways:
            break

        case .Denied:
            break

        default:
            break
        }
    }
}

然后我有这个班级

class CoreLocationController : NSObject {

    func requestLocationUpdate(delegate : CLLocationManagerDelegate){
        let locationManager = CLLocationManager()
        locationManager.delegate = delegate
        if #available(iOS 8.0, *) {
            locationManager.requestWhenInUseAuthorization()
        } else {
            locationManager.startUpdatingLocation()
        }

然后在AppDelegate中我声明它:

let coreLocationController = CoreLocationController()

但是当我从requestLocationUpdate(self)的孩子viewController调用UIViewLocationManager时,我没有收到任何更新。但是,如果我只是将所有方法复制粘贴到CoreLocationController并在locationManager.delegate = self方法中执行CoreLocationController init(),那么一切正常。

有什么想法吗?我真的很绝望,因为我已经尝试了很多方法,但仍然无法让这个工作。

提前致谢

1 个答案:

答案 0 :(得分:1)

locationManagerrequestLocationUpdate方法中的局部变量。在对requestLocationUpdate的调用结束时,locationManager将被销毁,而刚刚创建的CLLocationManager将无法引用它,因此它也会被销毁,尽管您已经问过它将消息发送到现存的delegate

如果您创建的CoreLocationController实例未被销毁 - 某些内容始终指向实例 - 那么将locationManager更改为实例变量应解决此问题:

class CoreLocationController : NSObject {
    var locationManager:CLLocationManager?
    func requestLocationUpdate(delegate : CLLocationManagerDelegate) {
        locationManager = CLLocationManager()
        locationManager?.delegate = delegate
        locationManager?.requestWhenInUseAuthorization()
    }
}

上面的代码在真正的iPhone 5和模拟的iPhone 6中为我工作。位置更新委托代码被调用。我必须按照CLLocation Manager in Swift to get Location of User

中的规定编辑plist