LoginSignup
5
11

More than 3 years have passed since last update.

【Swift】同期的にHTTP通信する

Posted at

ググったところ古い情報ばかり見つかったので、Swift5でも大丈夫だったよという記事

全2回のHTTPリクエストを行う際に、
2回目のリクエストは、1回目の通信結果を使用してパラメータを作るとかそういう用途で

環境

Xcode 11.3.1
Swift 5

方法

1.DispatchSemaphoreをvalue0で生成する
2.HTTP通信した直後、セマフォをwaitする
3.HTTP通信の完了イベント内でsignal()を呼び出す

ソースコード

    /// セマフォ
    var semaphore : DispatchSemaphore!

    func syncHttpRequest()
    {
        semaphore = DispatchSemaphore(value: 0)

        // Httpリクエストの生成
        var request = URLRequest(url: URL(string: "http://httpbin.org/get")!)
        request.httpMethod = "GET"

        // HTTPリクエスト実行
        URLSession.shared.dataTask(with: request, completionHandler: requestCompleteHandler).resume()

        // requestCompleteHandler内でsemaphore.signal()が呼び出されるまで待機する
        semaphore.wait()
        print("request completed")
    }

    func requestCompleteHandler(data:Data?,res:URLResponse?,err:Error?)
    {
        print("response recieve")
        semaphore.signal()
    }

実行結果

response recieve
request completed
5
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
5
11