LoginSignup
9

More than 5 years have passed since last update.

URLSessionを用いた通信

Posted at

背景

モバイルアプリ作っていると、APIで外部からデータを引っ張ってきたいと思うことが良くあります。
そういったときにAlamofireなどのサードパティーのライブラリを使いがちで、URLSessionを使ったことがない人がまあまあいると思います。そこでURLSessionを用いた基礎を書いていきます。

必要クラス

URLSession

ダウンロード周りのAPIを提供するクラス。

通信に必要なセッションを生成する。

URLSessionConfiguration

ダウンロードやアップロードする際、必ず設定すべき最初の手順。

バックグラウンド動作の有無や、タイムアウト時間など様々な設定をすることができる。

URLSessionTask

ファイルなどをダウンロードするなどのタスクが、URLSessionによって実行される。

下記のサブクラスによって振る舞いを決定することができる

  • URLSessionDataTask:ダウンロードする(小さいデータ)
  • URLSessionDownloadTask:ダウンロードする(大きなデータ)
  • URLSessionUploadTask:アップロードする

URLRequest

プロトコルまたはURLスキームに依存しないリクエストを行うことができる。

URLRequestを使わない場合GETメソッドでのリクエストしかできないが、
URLRequestを使うとPOSTメソッドでのリクエストを行うことがきる。

使い方

上記のクラスを用いてGETメソッドとPOSTメソッドでリクエストを投げる最小構成を書いていきます。

GETメソッド

class HTTPClient {
    func get() {
        let config: URLSessionConfiguration = URLSessionConfiguration.default
        let session: URLSession = URLSession(configuration: config)
        let url: URL = URL(string: "http://example.com")!

        session.dataTask(with: url, completionHandler: { (data, response, error) in
            // do something
        })
    }
}

let client: HTTPClient = HTTPClient()
client.get()

POSTメソッド

class HTTPClient {

    func post() {
        let config: URLSessionConfiguration = URLSessionConfiguration.default
        let session: URLSession = URLSession(configuration: config)
        let url: URL = URL(string: "http://example.com/post")!
        var req: URLRequest = URLRequest(url: url)
        req.httpMethod = "POST"
        req.httpBody = "post test".data(using: .utf8)

        let task = session.dataTask(with: req, completionHandler: { (data, response, error) in
            // do something
            print(error!)
        })
        task.resume()
    }
}

let client: HTTPClient = HTTPClient()
client.post()

GETでもPOSTでも書き方はほぼ同じで、POSTのときはURLRequestでhttp methodとhttp bodyの指定が必要です。

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
9