Receive data directly into memory by creating a data task from a URL session.
For small interactions with remote servers, you can use the URLSessionDataTask
class to receive response data into memory (as opposed to using the URLSessionDownloadTask
class, which stores the data directly to the file system). A data task is ideal for uses like calling a web service endpoint.
URLSessionDownloadTask
클래스를 사용하는 대신 URLSessionDataTask
클래스를 사용하여 응답 데이터를 메모리로 수신할 수 있습니다.You use a URL session instance to create the task. If your needs are fairly simple, you can use the shared
instance of the URLSession
class. If you want to interact with the transfer through delegate callbacks, you’ll need to create a session instead of using the shared instance. You use a URLSessionConfiguration
instance when creating a session, also passing in a class that implements URLSessionDelegate
or one of its subprotocols. Sessions can be reused to create multiple tasks, so for each unique configuration you need, create a session and store it as a property.
Note
Be careful to not create more sessions than you need. For example, if you have several parts of your app that need a similarly configured session, create one session and share it among them.
Once you have a session, you create a data task with one of the dataTask()
methods. Tasks are created in a suspended state, and can be started by calling resume()
.
The simplest way to fetch data is to create a data task that uses a completion handler. With this arrangement, the task delivers the server’s response, data, and possibly errors to a completion handler block that you provide. Figure 1 shows the relationship between a session and a task, and how results are delivered to the completion handler.