2016-11-29 3 views
0

Я пытаюсь запустить приложение простой геолокации, однако оно строит без ошибок, оно не обновляет мои данные о местоположении, как должно быть. Я использую скор 3, Xcode 8Приложение не обновляет мое местоположение

class CurrentLocationViewController: UIViewController, CLLocationManagerDelegate { 

let locationManager = CLLocationManager() 
var location: CLLocation? 

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

@IBOutlet weak var tagButton: UIButton! 

@IBAction func getMyLocation(_ sender: Any) { 
    let authStatus = CLLocationManager.authorizationStatus() 

    if authStatus == .notDetermined { 
     locationManager.requestWhenInUseAuthorization() 
     return 
    } 


    if authStatus == .denied || authStatus == .restricted { 
     showLocationServicesDeniedAlert() 
     return 
    } 


    locationManager.delegate = self 
    locationManager.desiredAccuracy = kCLLocationAccuracyNearestTenMeters 
    locationManager.startUpdatingLocation() 

    updateLabels() 



} 


    //Showing Alert message if location service is disabled 
    func showLocationServicesDeniedAlert() { 

     let alert = UIAlertController(title: "Location Services Disabled", message: "Please enable location services for this app in Settings.", preferredStyle: .alert) 

     let okAction = UIAlertAction(title: "OK", style: .default, handler: nil) 
     alert.addAction(okAction) 

     present(alert, animated: true, completion: nil) 


    } 



    //Updating Labels if Location is tutned on 

    func updateLabels() { 
     if let location = location { 
      latitudeLabel.text = String (format: "%.8f", location.coordinate.latitude) 
      longitudeLabel.text = String (format: "%.8f", location.coordinate.longitude) 
      tagButton.isHidden = false 
      messageLabel.text = "" 
     } else { 
      latitudeLabel.text = "" 
      longitudeLabel.text = "" 
      tagButton.isHidden = true 
      messageLabel.text = "Tap 'Get My Location' to Start" 
     } 
    } 


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

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

    //MARK: - CLLocationManagerDelegate 

    func locationManager (manager: CLLocationManager, didFailWithError error: NSError) { 
     print("didFailWithError \(error)") 


    } 


    func locationManager (manager: CLLocationManager, didUpdateLocations locations : [CLLocation]) { 
     let newLocation = locations.last! 
     print("didUpdateLocations \(newLocation)") 

     location = newLocation 
     updateLabels() 
    } 




} 

Я даже не могу поймать ошибки во время отладки, потому что, когда я пытаюсь написать печати в консоли нет ничего не происходит.

+0

Вы используете устройство или симулятор? –

+0

@ JacobKing Simulator –

ответ

0

Ваша проблема заключается в тестировании кода на основе местоположения на симуляторе. Хотя это возможно, симулятор имеет , а не, зная ваше местоположение, так как он не имеет доступа к любому оборудованию GPS.

Однако, это сама природа это Simulator и поэтому вы можете имитировать ваше местоположение. Это легко сделать, просто откройте симулятор и перейдите в Debug> Location, как показано на рисунке ниже.

enter image description here

Apple, дает нам пару встроенному в вариантах, но все они находятся в США, так что я хотел бы использовать пользовательский. Вам просто нужно нажать custom и ввести координату. Затем переустановите приложение и повторно разместите свое местоположение, и оно должно работать как ожидалось. Дайте мне знать, если это не так.

+0

Привет! Спасибо за ваш ответ. Однако это мне тоже не помогло. https://yadi.sk/i/uUoQn-a1zjG6W –

+0

Для меня это тоже выглядит странно, но я ничего не получаю в консоли отладки. –

+1

Включили ли вы свой 'NSLocationWhenInUseUsageDescription' ключ в свой' info.plist'? –

Смежные вопросы