2016-05-17 47 views
1

我在swift 2.0中遇到了問題LocationManager。它我的位置類:Swift 2.0 LocationManager是零

*

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創建對象:

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爲零太,我不知道爲什麼

+0

你正在模擬器上運行此? - 在真實的設備上測試它。 – Fennec

+0

你是否檢查didUpdateToLocation是否被調用 –

+1

當你第一次運行你的應用時,它是否顯示彈出來啓用位置? –

回答

0

你說:

coordinate?.latitude/longitudenil ...

如果locationManager不爲nil,但是coordinate是,這僅僅意味着您在位置管理員成功有機會檢索位置之前檢查coordinate。這可能需要幾秒鐘的時間。

...和我的locationManager也是nil

如果你叫locationManagerStart,但你後來查locationManager,這是nil,這意味着你可能有Location()兩個實例在你的代碼。確保您始終引用由應用程序代理創建的實例,並避免使用其他對Location()的引用。

另外,在applicationDidBecomeActive中實例化Location也會在某些情況下導致多個實例(因爲如果應用程序變爲非活動狀態並再次激活,您將再次實例化)。我建議在didFinishLaunchingWithOptions開始位置服務。我認爲這不是問題,但要注意這個問題。