我需要让用户动态获取当前位置。
为此,我正在使用CLLocationManager获取当前位置,这很好。
现在我想使用WIFI,GPS,定位服务或设备中的任何其他应用程序获取当前位置(即应用程序已经保持当前位置值)。
在上述所有可能的方式中,保持电池使用量减少以获得当前位置?
在iOS中怎么可能?
答案 0 :(得分:0)
将此代码放入Appdelegate
func initLocationManager() {
seenError = false
locationFixAchieved = false
locationManager = CLLocationManager()
locationManager.delegate = self
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestAlwaysAuthorization()
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
if (locationFixAchieved == false) {
locationFixAchieved = true
let locationArray = locations as NSArray
let locationObj = locationArray.lastObject as! CLLocation
let coord = locationObj.coordinate
NSUserDefaults.standardUserDefaults().setValue(String(coord.latitude), forKey: "latitude")
NSUserDefaults.standardUserDefaults().setValue(String(coord.longitude), forKey: "longitude")
locationManager.stopUpdatingLocation()
}
CLGeocoder().reverseGeocodeLocation(manager.location!, completionHandler: {(placemarks, error)->Void in
if (error != nil) {
print("Reverse geocoder failed with error" + error!.localizedDescription)
return
}
if placemarks!.count > 0 {
let pm = placemarks![0] as CLPlacemark
self.displayLocationInfo(pm)
} else {
print("Problem with the data received from geocoder")
}
})
}
func displayLocationInfo(placemark: CLPlacemark) {
//stop updating location to save battery life
locationManager.stopUpdatingLocation()
print(placemark.locality )
print(placemark.postalCode )
print(placemark.administrativeArea )
print(placemark.country )
NSUserDefaults.standardUserDefaults().setValue(placemark.locality, forKey: "city")
NSUserDefaults.standardUserDefaults().setValue(placemark.administrativeArea, forKey: "state")
}
// authorization status
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) {
print("Location to Allowed")
// Start location services
locationManager.startUpdatingLocation()
} else {
print("Denied access: \(locationStatus)")
}
}
现在在 didFinishLaunchingWithOptions
中调用 initLocationManager()类