[英]iOS swift Location Manager not getting updated properly
I am using CLLocationManager
for getting user location. 我正在使用CLLocationManager
获取用户位置。 I need to update user location when they move. 他们移动时,我需要更新用户位置。 I am using this code : 我正在使用此代码:
import UIKit
import CoreLocation
class ViewController: UIViewController, CLLocationManagerDelegate {
private var locationManager = CLLocationManager()
lazy var locations = [CLLocation]()
var op:String = ""
@IBOutlet weak var resultTxt: UITextView!
@IBAction func Start(sender: AnyObject) {
startLocationManager()
showResult()
}
override func viewDidLoad() {
super.viewDidLoad()
}
func startLocationManager(){
locationManager.delegate = self
locationManager.allowsBackgroundLocationUpdates = true
locationManager.distanceFilter = kCLDistanceFilterNone
locationManager.pausesLocationUpdatesAutomatically = false
locationManager.desiredAccuracy = kCLLocationAccuracyBest
locationManager.requestWhenInUseAuthorization()
locationManager.requestAlwaysAuthorization()
locationManager.startUpdatingLocation()
}
func startLocationTracking() {
NSLog("startLocationTracking")
if CLLocationManager.locationServicesEnabled() {
switch(CLLocationManager.authorizationStatus()) {
case .NotDetermined, .Restricted, .Denied:
print("No access")
self.startLocationManager()
case .AuthorizedAlways, .AuthorizedWhenInUse:
NSLog("authorizationStatus authorized")
}
} else {
print("Location services are not enabled")
self.startLocationManager()
}
}
func locationManager(manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) {
for location in locations {
let howRecent = location.timestamp.timeIntervalSinceNow
if abs(howRecent) < 10 && location.horizontalAccuracy < 20 {
//update distance
self.locations.append(location)
showResult()
}
}
}
func showResult(){
let currentDate = NSDate()
let res:String = "Result LAT : \(self.locations.last?.coordinate.latitude) AND LNG : \(self.locations.last?.coordinate.longitude) Time : \(currentDate.toShortTimeString()) \n "
op += res
self.resultTxt.text = op
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
}
And I have already added NSLocationAlwaysUsageDescription
and NSLocationWhenInUseUsageDescription
in .plist. 而且我已经在.plist中添加了NSLocationAlwaysUsageDescription
和NSLocationWhenInUseUsageDescription
。 This code works fine for the first time. 这段代码第一次正常工作。 But when the user moves " didUpdateLocations
" is not getting fired. 但是当用户移动“ didUpdateLocations
”时不会被解雇。 Can any one please help me, what I am doing wrong? 谁能帮我,我在做什么错?
Try to add these lines, to be able to monitoring significant location changes when user moves: 尝试添加以下行,以便能够在用户移动时监视重大的位置更改:
locationManager.startMonitoringSignificantLocationChanges()
locationManager.distanceFilter = 300 //value is up to you
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.