Swift 2.0 LocationManager 为零

Swift 2.0 LocationManager is nil

我对 swift 2.0 中的 LocationManager 有疑问。这是我的位置 Class :

*

import Foundation
import CoreLocation
class Location : NSObject,  CLLocationManagerDelegate {

    var locationManager: CLLocationManager?
    var coordinate: CLLocationCoordinate2D?


    func locationManagerStart() {

        if locationManager == nil {

            locationManager = CLLocationManager()
            locationManager?.delegate = self;
            locationManager?.desiredAccuracy = kCLLocationAccuracyBest
            locationManager?.requestWhenInUseAuthorization()
        }

        locationManager?.startUpdatingLocation()

    }

    func locationManagerStop() {

        locationManager?.stopUpdatingLocation()
    }

    //MARK: CLLocationManagerDelegate

    func locationManager(manager: CLLocationManager, didUpdateToLocation newLocation: CLLocation, fromLocation oldLocation: CLLocation) {

        coordinate = newLocation.coordinate

    }

*

我在 AppDelegate 中的这个 class 中创建对象:

let location = Location()

并在我的应用激活时开始位置:

func applicationDidBecomeActive(application: UIApplication) {


        location.locationManagerStart()

    }

稍后在我的代码中我需要检查我是否有权访问位置。我很痛苦,因为我在 iPhone 中有位置并且我接受使用我的位置:

 func haveAccessToLocation() -> Bool {

        if (coordinate?.latitude) != nil {

            return true

        }else {

            return false
        }

    }

我的 cordinate?.latitude/longitude 是零,我的 locationManager 也是零,我不知道为什么

你说:

My coordinate?.latitude/longitude is nil ...

如果 locationManager 不是 nil,但 coordinate 是,这仅意味着您在位置管理器成功获得机会之前检查 coordinate检索位置。这可能需要几秒钟。

... and my locationManager is nil, too.

如果您调用了 locationManagerStart,但您后来检查了 locationManager 并且它是 nil,这意味着您的代码中可能有两个 Location() 实例。确保您始终引用由应用程序委托创建的实例,并避免对 Location().

的其他引用

顺便说一句,在 applicationDidBecomeActive 中实例化 Location 在某些情况下也可能导致多个实例(因为如果应用程序变为非活动状态并再次活动,您将再次实例化它)。我建议在 didFinishLaunchingWithOptions 开始定位服务。我不认为这是这里的问题,但请注意这个问题。