2016-09-19 88 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