Class

URLSession

An object that coordinates a group of related, network data transfer tasks. 関連した、ネットワークデータ転送タスクの一群をうまく調整するオブジェクト。

Declaration 宣言

class URLSession : NSObject

Overview 概要

The URLSession class and related classes provide an API for downloading data from and uploading data to endpoints indicated by URLs. Your app can also use this API to perform background downloads when your app isn’t running or, in iOS, while your app is suspended. You can use the related URLSessionDelegate and URLSessionTaskDelegate to support authentication and receive events like redirection and task completion. URLSessionクラスと関連クラスは、データをURLによって指し示されるエンドポイントからダウンロードおよびそれへとアップロードするために、あるAPIを提供します。あなたのアプリはまたこのAPIを使ってバックグラウンドダウンロードを実行できるようにします、あなたのアプリが動作している時にまたは、iOSでは、あなたのアプリが一時停止される間に。あなたは関連したURLSessionDelegateURLSessionTaskDelegateを使うことで、認証をサポートして、リダイレクションおよびタスク完了のようなイベントを受け取ります。

Your app creates one or more URLSession instances, each of which coordinates a group of related data-transfer tasks. For example, if you’re creating a web browser, your app might create one session per tab or window, or one session for interactive use and another for background downloads. Within each session, your app adds a series of tasks, each of which represents a request for a specific URL (following HTTP redirects, if necessary). あなたのアプリは、1つ以上のURLSessionインスタンスを作成します、そのそれぞれが一群の関連する「データ転送」タスクを調整します。例えば、あなたがウェブブラウザを作成しているならば、あなたのアプリはタブまたはウインドウごとに1つのセッション、または相互作用利用に対して1つのセッションそしてバックグラウンドダウンロードに対してもう1つのものを作成するかもしれません。各セッション内で、あなたのアプリは一連のタスクを加えます、そのそれぞれは特定のURLに対するリクエストを表します(HTTPリダイレクトに従って、必要ならば)。

Types of URL Sessions URLセッションの型

The tasks within a given URL session share a common session configuration object, which defines connection behavior, like the maximum number of simultaneous connections to make to a single host, whether connections can use the cellular network, and so on. ある与えられたURLセッション内のタスクそれらは、ある共通セッション構成設定オブジェクトを共有します、それは接続挙動を定義します、たとえば単一のホストに行う同時接続の最大限の数、接続がセルラーネットワークを使うかどうか、など。

URLSession has a singleton shared session (which doesn’t have a configuration object) for basic requests. It’s not as customizable as sessions you create, but it serves as a good starting point if you have very limited requirements. You access this session by calling the shared class method. For other kinds of sessions, you create a URLSession with one of three kinds of configurations: URLSessionは、あるシングルトンsharedセッション(それは構成設定オブジェクトを持ちません)を基本的なリクエストに対して持ちます。それはあなたが作成するセッションと同じようにカスタマイズ可能ではありません、しかしそれはあなたが非常に制限された要件を持つならばひとつの良いスタート地点として用をなします。あなたはこのセッションに、共有クラスメソッドを呼び出すことによってアクセスします。他の種類のセッションに対して、あなたはURLSessionを3つの種類の構成設定で作成します:

  • A default session behaves much like the shared session, but lets you configure it. You can also assign a delegate to the default session to obtain data incrementally. 省略時のセッションは、ほとんど共有セッションのように振る舞います、しかしあなたがそれを構成設定するのを許可しません。あなたはまた、ある委任先を省略時のセッションに対して割り当てて、データを漸増的に入手できます。

  • Ephemeral sessions are similar to shared sessions, but don’t write caches, cookies, or credentials to disk. 短命セッションは、共有セッションに似ています、しかしキャッシュ、クッキー、または資格情報をディスクに書き出しません。

  • Background sessions let you perform uploads and downloads of content in the background while your app isn’t running. バックグラウンドセッションは、あなたに内容のアップロードとダウンロードをあなたのアプリが動作していない間にバックグラウンドで実行させます。

See Creating a Session Configuration Object in the URLSessionConfiguration class for details on creating each type of configuration. セッション構成設定オブジェクトを作成するURLSessionConfigurationクラスにおいて構成設定の各型を作成する上での詳細として見てください。

Types of URL Session Tasks URLセッションタスクの型

Within a session, you create tasks that optionally upload data to a server and then retrieve data from the server either as a file on disk or as one or more NSData objects in memory. The URLSession API provides four types of tasks: あるセッション内で、あなたはタスクそれらを作成します、それらは、随意にデータをサーバにアップロードします、そしてそれからデータをサーバから、ディスク上のファイルとしてまたはメモリ中の1つ以上のNSDataオブジェクトとして取って来ます。URLSession APIは、3つの型のタスクを提供します:

  • Data tasks send and receive data using NSData objects. Data tasks are intended for short, often interactive requests to a server. データタスクは、データをNSDataオブジェクトを使って送信および受信します。データタスクは、短い、多くの場合サーバへの対話型リクエストを期待されます。

  • Upload tasks are similar to data tasks, but they also send data (often in the form of a file), and support background uploads while the app isn’t running. アップロードタスクは、データタスクに似ています、しかしそれらはまたデータを送信します(しばしばファイルの形式で)、そしてバックグラウンドアップロードをアプリが動作していない間にサポートします。

  • Download tasks retrieve data in the form of a file, and support background downloads and uploads while the app isn’t running. ダウンロードタスクは、データをファイルの形式で撮ってきます、そしてバックグラウンドダウンロードとアップロードをアプリが動作していない間にサポートします。

  • WebSocket tasks exchange messages over TCP and TLS, using the WebSocket protocol defined in RFC 6455. WebSocketタスクは、メッセージをTCPおよびTLS越しに交換します、RFC 6455で定義されるWebSocketプロトコルを使います。

Using a Session Delegate セッション委任先を使う

Tasks in a session also share a common delegate object. You implement this delegate to provide and obtain information when various events occur, including when: あるセッションの中のタスクそれらはまた、ある共通委任先オブジェクトを共有します。あなたは、この委任先を実装することで、以下の場合を含む、さまざまなイベントが発生する場合に情報を提供および入手します:

  • Authentication fails. 認証が失敗する。

  • Data arrives from the server. データがサーバーから到着する。

  • Data becomes available for caching. データがキャッシュするために利用可能になる。

If you don’t need the features provided by a delegate, you can use this API without providing one by passing nil when you create a session. あなたが委任先によって提供される機能を必要としないならば、あなたはそれを提供することなしにこのAPIを使用することが、あなたがあるセッションを作成する時にnilを渡すことによって可能です。

Each task you create with the session calls back to the session’s delegate, using the methods defined in URLSessionTaskDelegate. You can also intercept these callbacks before they reach the session delegate by populating a separate delegate that’s specific to the task. あなたはまた、これらコールバックをそれらがセッション委任先に到達する前に横取りすることが、そのタスクに特有であるある分離したdelegateに放り込むことによって可能です。

Asynchronicity and URL Sessions 非同期性とURLセッション

Like most networking APIs, the URLSession API is highly asynchronous. It returns data to your app in one of three ways, depending on the methods you call: ほとんどのネットワークAPIのように、URLSession APIは高度に非同期です。それは、あなたが呼び出すメソッドに依存して、データをあなたのアプリへと3つの方法のうちの1つで返します:

  • If you’re using Swift, you can use the methods marked with the async keyword to perform common tasks. For example, data(from:delegate:) fetches data, while download(from:delegate:) downloads files. Your call point uses the await keyword to suspend running until the transfer completes. You can also use the bytes(from:delegate:) method to receive data as an AsyncSequence. With this approach, you use the for-await-in syntax to iterate over the data as your app receives it. The URL type also offers covenience methods to fetch bytes or lines from the shared URL session. あなたがSwiftを使っているならば、あなたはasyncキーワードで印されたメソッドを使って共通タスクを実行できます。例えば、data(from:delegate:)はデータを取ってきます、一方download(from:delegate:)はファイルをダウンロードします。あなたの呼び出し地点は、awaitキーワードを使って、転送が完了するまで実行を一時停止します。あなたはまた、bytes(from:delegate:)メソッドを使って、データをあるAsyncSequenceとして受け取ることができます。この取り組みでは、あなたはfor-await-in構文を使用することでデータじゅうを、あなたのアプリがそれを受け取るにつれて反復処理します。URL型はまた、便宜メソッドいくつかを共有URLセッションからバイトまたは行を取ってくるために提供します。

  • In Swift or Objective-C, you can provide a completion handler block, which runs when the transfer completes. SwiftまたはObjective-Cにおいて、あなたはある完了ハンドラブロックを提供できます、それは転送が完了する時に実行されます。

  • In Swift or Objective-C, you can receive callbacks to a delegate method as the transfer progresses and immediately after it completes. SwiftまたはObjective-Cでは、あなたはある委任先メソッドへのコールバックそれらを転送が進捗するにつれてそしてそれが完了する直後に受け取ることができます。

In addition to delivering this information to delegates, the URLSession provides status and progress properties. Query these properties if you need to make programmatic decisions based on the current state of the task (with the caveat that its state can change at any time). これらのプロパティに問いただしてください、あなたがプログラム的な決定を(それの状態がいつでも変わりうるという警告つきの)タスクの現在の状態に基づいてする必要があるならば。

Protocol Support プロトコルサポート

The URLSession class natively supports the data, file, ftp, http, and https URL schemes, with transparent support for proxy servers and SOCKS gateways, as configured in the user’s system preferences. URLSessionクラスは、datafileftphttp、そしてhttps URLスキームを生得的にサポートします、プロキシサーバーとSOCKSゲイトウェイに対する透過的なサポートとともに。

URLSession supports the HTTP/1.1, HTTP/2, and HTTP/3 protocols. HTTP/2 support, as described by RFC 7540, requires a server that supports Application-Layer Protocol Negotiation (ALPN). HTTP/2サポートは、RFC 7540で記述されるように、Application-Layer Protocol Negotiation (ALPN) をサポートするサーバーを必要とします。

You can also add support for your own custom networking protocols and URL schemes (for your app’s private use) by subclassing URLProtocol. あなたはまた、あなた独自のあつらえのネットワークプロトコルとURLスキームに対するサポートを(あなたのアプリのもつプライベートな利用のために)URLProtocolのサブクラスを作ることによって追加できます。

App Transport Security (ATS)

iOS 9.0 and macOS 10.11 and later use App Transport Security (ATS) for all HTTP connections made with URLSession. ATS requires that HTTP connections use HTTPS (RFC 2818). iOS 9.0およびmacOS 10.11およびそれより後ではApp Transport Security (ATS) をURLSessionで作られる全てのHTTP接続に対して使ってください。ATSは、HTTP接続がHTTPS(RFC 2818)を使うことを必要とします。

For more information, see NSAppTransportSecurity. さらなる情報として、NSAppTransportSecurityを見てください。

Foundation Copying Behavior Foundationコピー挙動

Session and task objects conform to the NSCopying protocol as follows: セッションおよびタスクオブジェクトは、NSCopyingプロトコルに以下のように準拠します:

  • When your app copies a session or task object, you get the same object back. あなたのアプリがセッションまたはタスクオブジェクトをコピーする時、あなたは同じオブジェクトを取り戻します。

  • When your app copies a configuration object, you get a new copy you can independently modify. あなたのアプリが構成設定オブジェクトをコピーする時、あなたは、あなたが独立して修正できるある新しい複製を得ます。

Thread Safety スレッド安全

The URL session API is thread-safe. You can freely create sessions and tasks in any thread context. When your delegate methods call the provided completion handlers, the work is automatically scheduled on the correct delegate queue. URLセッションAPIは、スレッド安全です。あなたは、自由にセッションとタスクをあらゆるスレッドコンテキストにおいて作成できます。あなたの委任先メソッドがその提供された完了ハンドラを呼び出す時、その仕事は自動的に正しい委任先キュー上で予定されます。

Topics 話題

Using the Shared Session 共有セッションを使う

Creating a Session セッションを作成する

Working with a Delegate 委任先を扱う

Performing Asynchronous Transfers 非同期転送を実行する

Adding Data Tasks to a Session データタスクをセッションに加える

Adding Download Tasks to a Session ダウンロードタスクをセッションに加える

Adding Upload Tasks to a Session アップロードタスクをセッションに加える

Adding Stream Tasks to a Session ストリームタスクをセッションに加える

Adding WebSocket Tasks to a Session WebSocketタスクをセッションに加える

Managing the Session セッションを管理する

Handling Errors エラーを取り扱う

Performing Tasks as a Combine Publisher タスクをCombineパブリッシャーとして実行する

Initializers イニシャライザ

Type Methods 型メソッド

Relationships 関係

Inherits From 継承元

See Also 参照

Essentials 要点