2017-10-31 18 views
2

Alamofire가 포함 된 SPM으로 작성된 매우 간단한 프로젝트를 사용하고 있습니다.클로저 쓰레드가 완료 될 때까지 기다려야합니다.

main.swift : 나는 잠금을 사용하지 않으면 폐쇄가 실행되지 않습니다

import Alamofire 

Alamofire.request("https://google.com").responseString(queue: queue) { response in 
      print("\(response.result.isSuccess)") 
} 

. 종료하기 전에 모든 스레드 또는 해당 스레드를 기다리는 방법이 있습니까?

놀이터를 사용하면 쉽게 달성 할 수 있습니다. , 또는

let semaphore = DispatchSemaphore(value: 0) 

doSomethingAsync { 
    semaphore.signal() 
} 

semaphore.wait() 

// your code will not get here until the async task completes 

여러 작업을 위해 대기하는 경우, 당신은 디스패치 그룹을 사용할 수 있습니다 :

let group = DispatchGroup() 

group.enter() 
doAsyncTask1 { 
    group.leave() 
} 

group.enter() 
doAsyncTask2 { 
    group.leave() 
} 

group.wait() 

// You won't get here until all your tasks are done 

답변

2

가장 간단한 방법은 세마포어를 사용하는 것입니다 Swift 용 3

let group = DispatchGroup() 
group.enter() 
DispatchQueue.global(qos: .userInitiated).async { 
    // Do work asyncly and call group.leave() after you are done 
    group.leave() 
} 
group.notify(queue: .main, execute: { 
    // This will be called when block ends    
}) 

이 코드는 이후에 일부 코드를 실행해야 할 때 유용합니다. 내 작업이 완료되었습니다.

귀하의 질문에 대한 자세한 내용을 적어 주시면 더 자세히 도와 드리겠습니다.

0

를 비동기 작업을 기다리는