2014-11-27 5 views
0

CLLocationManagerCLLocation을 사용하여 내 앱에서 iOS 기기의 현재 위치를 가져옵니다. 그게 잘 작동 해. 제공된 위치 매개 변수 latitudelongitude 다른 자체 생성 함수에 사용하고 싶습니다. 그러나 문제는 현재 위치를 가져 오는 내 함수가 비동기 프로세스에서 실행되고 다음 함수를 시작하는 동안 완료되지 않는다는 것입니다.iOS 앱에서 현재 위치를 가져 오는 비동기 프로세스 완료 대기

현재 위치를 가져 오는보기 컨트롤러에서 대리인을 사용합니다.

var latitude:CLLocationDegrees = 0.0 
var longitude:CLLocationDegrees = 0.0 

override func viewDidLoad() { 
    super.viewDidLoad() 

    //get the current location and set vars latitude and logitude with right values 
    self.getCurrentLocation() 

    //compute distance from current location to given location 
    //the result of getCurrentLocation() still not exists at this time 
    //latitude and longitude still have the value 0.0 and not the real value set by getCurrentLocation() 
    self.computeDistanceToGivenLocation(anotherLatitude: 10.0, anotherLogitude: 15.0) 
} 

어떻게 내 기능 getCurrentLocation() 다음 기능 self.computeDistanceToGivenLocation()와 코드에 가기 전에 완료 될 때까지 기다릴 수 있습니다 : 여기

는 신속 내 코드?

+0

그렇게하지 마십시오. 전체 UI를 차단합니다. 위치 관리자 대리자 메소드에서 'computeDistanceToGivenLocation ...'을 호출해야합니다. 즉 일단 위치 정보가 있으면 Delegate 메소드의 UI 업데이트를 기본 대기열에 디스패치해야 함 – Paulw11

답변

1

저는 이것을 수행하기 위해 클로저/블록을 사용할 수 있다고 생각합니다. Cocoa 프레임 워크에서 completionHandler와 같은 이름으로 많은 것을 볼 수 있습니다.

그래서 클로저/블록을 인수로 사용하는 방식으로 getCurrentLocation() 메서드를 수정하십시오. 이 블록에는 self.computeDistanceToGivenLocation() 호출이 포함됩니다. 그런 다음 getCurrentLocation()의 끝에서 단순히 클로저/블록을 사용합니다. 문법은 약간 까다 롭고 빨리 시작할 필요가 없습니다. 여기에 documentation입니다.

하지만 getCurrentLocation()이 실제로하는 일은 확실하지 않습니다. 위치 업데이트를 시작하기 만하면 위치 관리자에게 알려주는 것입니까? 그런 다음 위와 같은 방법으로 만 computeDistanceToGivenLocation()을에서 직접 호출해야한다고 생각해야합니다. 왜냐하면 위와 같은 방법으로 위치 데이터가 100 % 확실 할 수 있기 때문입니다.