2016-06-16 8 views
0

私はCLLocationManagerを使用してユーザーの所在地を取得しています。移動するときにユーザーの場所を更新する必要があります。私はこのコードを使用しています:iOS swift Location Managerが正しく更新されない

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() 
    } 

} 

を私はすでにの.plistでNSLocationAlwaysUsageDescriptionNSLocationWhenInUseUsageDescriptionを追加しました。 このコードは初めて正常に動作します。しかし、ユーザーが "didUpdateLocations"を動かすと、解雇されません。 誰かが私を助けてくれますか、私が間違っていることはありますか?

答えて

0

は、ときに、ユーザーが移動する重要な場所の変更を監視することができるように、これらの行を追加してください:

locationManager.startMonitoringSignificantLocationChanges() 
locationManager.distanceFilter = 300 //value is up to you 
+0

Sorry.It年代が機能していない... – Rupshikha

+0

を使用すると、場所の変更をシミュレートしようとしたことがありますか?これはiOS Simulatorで直接行うことができます。 –

+0

雅...私は... – Rupshikha

関連する問題