[iOS] DispatchSemaphore 정리

HL·2022년 5월 14일
0

iOS

목록 보기
22/22

네트워크 요청을 동기적으로 수행하고 싶어 찾아봤다


count가 0일 때 작업 실행

  • signal() >> count += 1
  • wait() >> count -= 1

코드 예시

        let semaphore = DispatchSemaphore(value: 0)

        while true {
            guard let url = URL(string: urlString) else { return }
            var request = URLRequest(url: url)
            
            URLSession.shared.dataTask(with: request) {
                (data: Data?, response: URLResponse?, error: Error?) in
                
                print("전송후 events.count: \(events.count)")
                
                semaphore.signal() // count 1됨 >> 멈춤
                
            }.resume()
            
            semaphore.wait() // count 0됨 >> 실행
        }
        

근데 백그라운드에서 처리하고 싶었는데 모두 처리할때까지 멈춰버린다
더 찾아봐야겠다

profile
Frontend 개발자입니다.

0개의 댓글