2016-09-19 125 views
0

我在AppDelegate中獲取用戶的經度和緯度,它在我刪除時請求了一次權限\在模擬器上再次重新安裝後卸載應用程序它沒有要求權限,所以應用程序在這裏繼續崩潰是我的代碼Iphone模擬器沒有獲取位置

func initLocationManager() { 

    if(CLLocationManager.authorizationStatus() == CLAuthorizationStatus.AuthorizedWhenInUse || 
     CLLocationManager.authorizationStatus() == CLAuthorizationStatus.Authorized){ 

     seenError = false 
     locationFixAchieved = false 
     locationManager = CLLocationManager() 
     locationManager.delegate = self 
     //  locationManager.locationServicesEnabled = true 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.startUpdatingLocation() 
     locationManager.requestAlwaysAuthorization() 

    } 
} 

// Location Manager Delegate stuff 

func locationManager(manager: CLLocationManager!, didFailWithError error: NSError!) { 
    locationManager.stopUpdatingLocation() 
    if ((error) != nil) { 
     if (seenError == false) { 
      seenError = true 
      print(error) 
     } 
    } 
} 

func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    if (locationFixAchieved == false) { 
     locationFixAchieved = true 
     var locationArray = locations as NSArray 
     var locationObj = locationArray.lastObject as! CLLocation 
     var coord = locationObj.coordinate 

     LATITUDE = coord.latitude 
     LONGITUDE = coord.longitude 

     print(coord.latitude) 
     print(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)") 
    } 
} 
+0

所以它不會在模擬器上工作? –

+0

它仍然沒有工作。我怎樣才能獲得用戶位置迅速 –

+0

你在哪裏調用'requestWhenInUseAuthorization'? – Paulw11

回答

1

嘗試第一次獲取用戶在didFinishLaunchingWithOptions的位置,然後調用此方法獲取更新的用戶位置。

locationManager = CLLocationManager() 
locationManager.delegate = self 
locationManager.desiredAccuracy = kCLLocationAccuracyBest 
locationManager.requestAlwaysAuthorization() 
locationManager.startUpdatingLocation() 


func locationManager(manager:CLLocationManager, didUpdateLocations locations:AnyObject[]) { 
println("locations = \(locations)") 
gpsResult.text = "success" 
} 
+0

但用戶位置每次都會更改 –

+0

每次啓動應用程序時我都想獲取用戶位置 –

+0

我的答案適用於每次獲取用戶位置該應用程序已啓動。獲得更新的用戶位置呼叫 – user3189586