2017-10-07 13 views
0

pourquoi ce code ne fonctionne pas? Je suppose que c'est quelque chose avec didUpdateLocations méthode surfait? Comment puis-je correctement les connecter avec mes étiquettes et leur faire un live :)Swift 4 CoreLocation ne fonctionne pas

import UIKit 
import CoreLocation 

class MainVC: UIViewController, CLLocationManagerDelegate { 

var walking = false 
var pause = false 
var locationManager: CLLocationManager = CLLocationManager() 
var startLocation: CLLocation! 
var speed: CLLocationSpeed = CLLocationSpeed() 

@IBOutlet weak var latitudeLabel: UILabel! 
@IBOutlet weak var longitudeLabel: UILabel! 

@IBOutlet weak var horizontalAccuracyLabel: UILabel! 
@IBOutlet weak var verticalAccuracyLabel: UILabel! 

@IBOutlet weak var distanceLabel: UILabel! 
@IBOutlet weak var altitudeLabel: UILabel! 

@IBOutlet weak var speedLabel: UILabel! 

override func viewDidLoad() { 
    super.viewDidLoad() 
    // Do any additional setup after loading the view, typically from a nib. 

    locationManager.desiredAccuracy = kCLLocationAccuracyBest 
    locationManager.delegate = self 
    locationManager.requestWhenInUseAuthorization() 
    locationManager.startUpdatingLocation() 
    locationManager.startUpdatingHeading() 
    startLocation = nil 

    // Ask for Authorisation from the User. 
    self.locationManager.requestAlwaysAuthorization() 

    // For use in foreground 
    self.locationManager.requestWhenInUseAuthorization() 

    if CLLocationManager.locationServicesEnabled() { 
     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 
     locationManager.startUpdatingLocation() 
    } 
} 

override func didReceiveMemoryWarning() { 
    super.didReceiveMemoryWarning() 
    // Dispose of any resources that can be recreated. 
} 

@IBAction func startDistance(_ sender: UIButton) { 
    startLocation = nil 
    walking = true 
} 

@IBAction func stopDistance(_ sender: UIButton) { 
    walking = false 
} 

@IBAction func resetDistance(_ sender: UIButton) { 
    startLocation = nil 
} 

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 

    let latestLocation: AnyObject = locations[locations.count - 1] 

    latitudeLabel.text = String(format: "%.4f",latestLocation.coordinate.latitude) 
    longitudeLabel.text = String(format: "%.4f",latestLocation.coordinate.longitude) 

    horizontalAccuracyLabel.text = String(format: "%.4f",latestLocation.horizontalAccuracy) 
    verticalAccuracyLabel.text = String(format: "%.4f",latestLocation.verticalAccuracy) 

    altitudeLabel.text = String(format: "%.4f",latestLocation.altitude) 

    if walking == true { 
     if startLocation == nil { 
      startLocation = latestLocation as! CLLocation 
      speed = locationManager.location!.speed 
      speedLabel.text = String(format: "%.0f km/h", speed * 3.6) 
     } 

     let distanceBetween: CLLocationDistance = 
      latestLocation.distance(from: startLocation) 

     distanceLabel.text = String(format: "%.2f", distanceBetween) 
    } 
} 


func locationManager(_ manager: CLLocationManager, didUpdateHeading newHeading: CLHeading) 
{ 
// capLabel.text = String(format: "%.4f",newHeading.magneticHeading) 
} 


func locationManager(_ manager: CLLocationManager, didFailWithError error: Error) { 

} 

} 

J'ai aussi ajouté: Toujours Localisation Utilisation Description dans mon info.plist Et j'admis Situation dans les paramètres de mon simulateur aussi.

Merci.

+0

Je reçois exactement le même problème. Après le débogage, je crois que didUpdateLocations n'appelle pas pour une raison quelconque. –

+0

Définir "ne fonctionne pas". C'est une description inutile. [Modifier] votre question pour expliquer clairement en quoi votre code ne fait pas ce que vous attendez. Recevez-vous des erreurs/avertissements du compilateur? L'application plante-t-elle? Des messages d'erreur? Est-ce que le code ne fonctionne pas comme prévu? Est-ce le cas, de quelle manière? Soyez clair et précis à propos de votre problème. – rmaddy

+0

Essayez d'exécuter le code dans un périphérique réel. Ou utilisez la fonctionnalité de débogage de l'emplacement du simulateur. – Aks

Répondre

0

Pour configurer toujours l'autorisation de Swift 4 pour les services de localisation que je peux voir que vous avez écrit dans votre code self.locationManager.requestAlwaysAuthorization(), procédez comme suit:

Il y a une nouvelle clé NSLocationAlwaysAndWhenInUsageDescription qui est également nécessaire dans votre info.plist

<key>NSLocationAlwaysUsageDescription</key> 
    <string> location permission text.</string> 
<key>NSLocationWhenInUseUsageDescription</key> 
    <string> location permission text.</string> 
<key>NSLocationAlwaysAndWhenInUseUsageDescription</key> 
    <string> location permission text.</string> 

Jetez un oeil dans la documentation here

Vous devez inclure les NSLocationWhenInUseUsageDescription et NSLocationAlwaysAndWhenInUsageDescription clés dans fichier Info.plist de votre application. (Si votre application prend en charge iOS 10 et les versions antérieures, la clé NSLocationAlwaysUsageDescription est également requise.) Si les clés ne sont pas présentes, les demandes d'autorisation échouent immédiatement.

Nous allons donc avoir une seule invite maintenant. enter image description here