2016-12-05 3 views
4

위치 데이터를 사용하여 간단한 iOS 앱을 만들고 싶습니다. 불행히도, 장치 및 시뮬레이터에서 테스트하는 동안 시뮬레이터에서 "현재 위치"디버그 코드를 입력하더라도 'nil'을 수신합니다. 스위프트 3에서 CoreLocation을 처음 사용하기 때문에 이전에 사용했던 것과 같은 방식을 사용했습니다.위치 신속 문제 3

import UIKit 
import CoreLocation 

class ViewController: UIViewController, CLLocationManagerDelegate { 

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

    var locationManager:CLLocationManager? 
    var currentLocation:CLLocation? 

    override func viewDidLoad() { 
     super.viewDidLoad() 
     let locationManager = CLLocationManager() 
     locationManager.delegate = self 
     locationManager.desiredAccuracy = kCLLocationAccuracyBest 
     locationManager.requestAlwaysAuthorization() 
     locationManager.startUpdatingLocation() 
     updateLabels() 
     // Do any additional setup after loading the view, typically from a nib. 
    } 

    func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
     self.currentLocation = locations[0] 
    } 

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

    func updateLabels() { 
     latitudeLabel.text = String(describing: currentLocation?.coordinate.latitude) 
     longitudeLabel.text = String(describing: currentLocation?.coordinate.longitude) 
     print(currentLocation) 
} 

} 

물론 저는 Info.plist에 필요한 개인 키를 모두 작성했습니다.

currentLocation을 인쇄하려고 할 때 나는 nil을받습니다. 마지막 출시와 함께 경고가 표시되는 것보다 그러한 문제가 발견되었지만 즉시 사라졌습니다.

+0

당신은 "나는 '전무'를받을"이란 무엇을 의미합니까? 문제를 분명히하십시오. 응답을 위해 – rmaddy

+0

주셔서 감사합니다. 편집 된 설명. –

답변

4

viewDidLoad에서 CLLocationManager은 로컬 변수에 저장하지만 속성에는 저장하지 마십시오. 따라서 범위를 벗어나 할당이 해제되어 대리자 메서드를 호출하지 않을 가능성이 있습니다.

직접 속성을 업데이트하거나 위치 관리자 구성을 마쳤 으면 self.locationManager = locationManager을 수행해야합니다.

override func viewDidLoad() { 
    super.viewDidLoad() 

    locationManager = CLLocationManager() 
    locationManager?.delegate = self 
    locationManager?.desiredAccuracy = kCLLocationAccuracyBest 
    locationManager?.requestAlwaysAuthorization() 
    locationManager?.startUpdatingLocation() 
    // updateLabels() 
} 

을 그리고 rmaddy가 지적했듯이 다음, didUpdateLocations에 라벨을 업데이트 : 아마 직접 업데이트 할 것

func locationManager(_ manager: CLLocationManager, didUpdateLocations locations: [CLLocation]) { 
    guard let location = locations.last, location.horizontalAccuracy >= 0 else { return } 

    currentLocation = location 
    updateLabels() 
} 
1

updateLabels은 잘못된 장소에서 호출했습니다. locationManager(_:didUpdateLocations) 메서드 내부에서 호출해야합니다. 그리고 그 위임 메서드는 백그라운드 스레드에서 호출 될 수 있기 때문에 DispatchQueue.main.async을 사용하여 updateLabels에 대한 호출을 감싸야합니다.