0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 1 year has passed since last update.

【Swift】URLSessionについて

Posted at

URLSessionとは

関連するネットワーク データ転送タスクのグループを調整するオブジェクトです。

アプリは 1 つ以上のURLSessionインスタンスを作成し、それぞれが関連するデータ転送タスクのグループを調整します。たとえば、Web ブラウザーを作成している場合、アプリはタブまたはウィンドウごとに 1 つのセッションを作成するか、インタラクティブな使用のために 1 つのセッションを作成し、バックグラウンド ダウンロード用に別のセッションを作成することがあります。各セッション内で、アプリは一連のタスクを追加します。各タスクは、特定の URL に対する要求を表します (必要に応じて HTTP リダイレクトに従います)。

例文

UrlSessionは、デフォルトのセッション、エフェメラルセッション、バックグラウンドセッションの3つの種類があり、それぞれ異なる目的に使用されます。

デフォルトのセッション

永続的なキャッシュや認証情報を利用するために使用されます。

エフェメラルセッション

キャッシュやクッキーを保存しない一時的なセッションで、プライバシーに関連するリクエストに使用されます。

バックグラウンドセッション

アプリがバックグラウンドで実行されている場合にもネットワークが途切れないセッションです。

デフォルトのセッションの作成

let url = URL(string: "https://example.com")!

let task = URLSession.shared.dataTask(with: url) { (data, response, error) in

    // 処理結果を取得する

}

task.resume()

エフェメラルセッションの作成

let configuration = URLSessionConfiguration.ephemeral

let session = URLSession(configuration: configuration)

let url = URL(string: "https://example.com")!

let task = session.dataTask(with: url) { (data, response, error) in

    // 処理結果を取得する

}

task.resume()

バックグラウンドセッションの作成

let configuration = URLSessionConfiguration.background(withIdentifier: "com.example.background")

let session = URLSession(configuration: configuration, delegate: self, delegateQueue: nil)

let url = URL(string: "https://example.com")!

let task = session.downloadTask(with: url)

task.resume()
  </div>

最後に

iOSアプリ開発をしています。
主にSwiftですが、最近は熱が入ってきてFlutterも🦾
色々やってます。もし良かったら見てってください。

0
0
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
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?