1. URLSessionDelegate
optional public func urlSession(_ session: URLSession,
didBecomeInvalidWithError error: Error?)
Tells the URL session that the session has been invalidated.
If you invalidate a session by calling its finishTasksAndInvalidate() method, the session waits until after the final task in the session finishes or fails before calling this delegate method. If you call the invalidateAndCancel() method, the session calls this delegate method immediately.
public func urlSession(_ session: URLSession,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void)
Requests credentials from the delegate in response to a session-level authentication request from the remote server.
This method is called in two situations:
- When a remote server asks for client certificates or Windows NT LAN Manager (NTLM) authentication, to allow your app to provide appropriate credentials
- When a session first establishes a connection to a remote server that uses SSL or TLS, to allow your app to verify the server’s certificate chain
If you do not implement this method, the session calls its delegate’s
urlSession(_:task:didReceive:completionHandler:)
method instead.
public func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession)
Tells the delegate that all messages enqueued for a session have been delivered.
In iOS, when a background transfer completes or requires credentials, if your app is no longer running, your app is automatically relaunched in the background, and the app’s UIApplicationDelegate is sent an application(_:handleEventsForBackgroundURLSession:completionHandler:) message. This call contains the identifier of the session that caused your app to be launched. Your app should then store that completion handler before creating a background configuration object with the same identifier, and creating a session with that configuration. The newly created session is automatically reassociated with ongoing background activity.When your app later receives a URLSessionDidFinishEventsForBackgroundURLSession: message, this indicates that all messages previously enqueued for this session have been delivered, and that it is now safe to invoke the previously stored completion handler or to begin any internal updates that may result in invoking the completion handler.
Important
Because the provided completion handler is part of UIKit, you must call it on your main thread.
For example:
[[NSOperationQueue mainQueue] addOperationWithBlock:^{ storedHandler(); }];
2. URLSessionTaskDelegate
public func urlSession(_ session: URLSession,
task: URLSessionTask,
willPerformHTTPRedirection response: HTTPURLResponse,
newRequest request: URLRequest,
completionHandler: @escaping (URLRequest?) -> Swift.Void)
Tells the delegate that the remote server requested an HTTP redirect.
This method is called only for tasks in default and ephemeral sessions. Tasks in background sessions automatically follow redirects.
public func urlSession(_ session: URLSession,
task: URLSessionTask,
didReceive challenge: URLAuthenticationChallenge,
completionHandler: @escaping (URLSession.AuthChallengeDisposition, URLCredential?) -> Swift.Void)
Requests credentials from the delegate in response to an authentication request from the remote server.
This method handles task-level authentication challenges. The URLSessionDelegate protocol also provides a session-level authentication delegate method. The method called depends on the type of authentication challenge:
- For session-level challenges—NSURLAuthenticationMethodNTLM, NSURLAuthenticationMethodNegotiate, NSURLAuthenticationMethodClientCertificate, or NSURLAuthenticationMethodServerTrust—the NSURLSession object calls the session delegate’s urlSession(:didReceive:completionHandler:) method. If your app does not provide a session delegate method, the NSURLSession object calls the task delegate’s urlSession(:task:didReceive:completionHandler:) method to handle the challenge.
- For non-session-level challenges (all others), the NSURLSession object calls the session delegate’s urlSession(:task:didReceive:completionHandler:) method to handle the challenge. If your app provides a session delegate and you need to handle authentication, then you must either handle the authentication at the task level or provide a task-level handler that calls the per-session handler explicitly. The session delegate’s urlSession(:didReceive:completionHandler:) method is not called for non-session-level challenges.
optional public func urlSession(_ session: URLSession,
task: URLSessionTask,
needNewBodyStream completionHandler: @escaping (InputStream?) -> Swift.Void)
Tells the delegate when a task requires a new request body stream to send to the remote server.
This delegate method is called under two circumstances:
- To provide the initial request body stream if the task was created with uploadTask(withStreamedRequest:)
- To provide a replacement request body stream if the task needs to resend a request that has a body stream because of an authentication challenge or other recoverable server error.
Note
You do not need to implement this if your code provides the request body using a file URL or an NSData object.
optional public func urlSession(_ session: URLSession,
task: URLSessionTask,
didSendBodyData bytesSent: Int64,
totalBytesSent: Int64,
totalBytesExpectedToSend: Int64)
Periodically informs the delegate of the progress of sending body content to the server.
optional public func urlSession(_ session: URLSession,
task: URLSessionTask,
didFinishCollecting metrics: URLSessionTaskMetrics)
Tells the delegate that the session finished collecting metrics for the task.
URLSessionTaskMetrics
- An NSURLSessionTaskMetrics object encapsulates the metrics for a session task. Each object contains the taskInterval and redirectCount, as well as metrics for each request / response transaction made during the execution of the task.
optional public func urlSession(_ session: URLSession,
task: URLSessionTask,
didCompleteWithError error: Error?)
Tells the delegate that the task finished transferring data.
Server errors are not reported through the error parameter. The only errors your delegate receives through the error parameter are client-side errors, such as being unable to resolve the hostname or connect to the host.
3. URLSessionDataDelegate
optional public func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive response: URLResponse,
completionHandler: @escaping (URLSession.ResponseDisposition) -> Swift.Void)
Tells the delegate that the data task received the initial reply (headers) from the server.
This method is optional unless you need to support the (relatively obscure) multipart/x-mixed-replace content type. With that content type, the server sends a series of parts, each of which is intended to replace the previous part. The session calls this method at the beginning of each part, and you should then display, discard, or otherwise process the previous part, as appropriate.
If you do not provide this delegate method, the session always allows the task to continue.
optional public func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome downloadTask: URLSessionDownloadTask)
Tells the delegate that the data task was changed to a download task.
When the delegate’sURLSession:dataTask:didReceiveResponse:completionHandler:
method decides to change the disposition from a data request to a download, the session calls this delegate method to provide you with the new download task. After this call, the session delegate receives no further delegate method calls related to the original data task.
optional public func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didBecome streamTask: URLSessionStreamTask)
Tells the delegate that the data task was changed to a streamtask.
When the delegate’sURLSession:dataTask:didReceiveResponse:completionHandler:
method decides to change the disposition from a data request to a stream, the session calls this delegate method to provide you with the new stream task. After this call, the session delegate receives no further delegate method calls related to the original data task.For requests that were pipelined, the stream task will only allow reading, and the object will immediately send the delegate message urlSession(_:writeClosedFor:). Pipelining can be disabled for all requests in a session by setting the httpShouldUsePipelining property on its URLSessionConfiguration object, or for individual requests by setting the httpShouldUsePipelining property on an NSURLRequest object.
optional public func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
didReceive data: Data)
Tells the delegate that the data task has received some of the expected data.
Because the NSData object is often pieced together from a number of different data objects, whenever possible, use NSData’s enumerateBytes(_:) method to iterate through the data rather than using the bytes method (which flattens the NSData object into a single memory block).
This delegate method may be called more than once, and each call provides only data received since the previous call. The app is responsible for accumulating this data if needed.
optional public func urlSession(_ session: URLSession,
dataTask: URLSessionDataTask,
willCacheResponse proposedResponse: CachedURLResponse,
completionHandler: @escaping (CachedURLResponse?) -> Swift.Void)
Asks the delegate whether the data (or upload) task should store the response in the cache.
The session calls this delegate method after the task finishes receiving all of the expected data. If you do not implement this method, the default behavior is to use the caching policy specified in the session’s configuration object. The primary purpose of this method is to prevent caching of specific URLs or to modify the userInfo dictionary associated with the URL response.
This method is called only if the URLProtocol handling the request decides to cache the response. As a rule, responses are cached only when all of the following are true:
- The request is for an HTTP or HTTPS URL (or your own custom networking protocol that supports caching).
- The request was successful (with a status code in the 200–299 range).
- The provided response came from the server, rather than out of the cache.
- The session configuration’s cache policy allows caching.
- The provided NSURLRequest object's cache policy (if applicable) allows caching.
- The cache-related headers in the server’s response (if present) allow caching.
- The response size is small enough to reasonably fit within the cache. (For example, if you provide a disk cache, the response must be no larger than about 5% of the disk cache size.)
4. URLSessionDownloadDelegate
public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didFinishDownloadingTo location: URL)
Tells the delegate that a download task has finished downloading.
Sent when a download task that has completed a download. The delegate should copy or move the file at the given location to a new location as it will be removed when the delegate message returns. URLSession:task:didCompleteWithError: will still be called.
optional public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didWriteData bytesWritten: Int64, totalBytesWritten: Int64,
totalBytesExpectedToWrite: Int64)
Periodically informs the delegate about the download’s progress.
optional public func urlSession(_ session: URLSession,
downloadTask: URLSessionDownloadTask,
didResumeAtOffset fileOffset: Int64,
expectedTotalBytes: Int64)
Tells the delegate that the download task has resumed downloading.
If a resumable download task is canceled or fails, you can request a resumeData object that provides enough information to restart the download in the future. Later, you can call
downloadTask(withResumeData:)
ordownloadTask(withResumeData:completionHandler:)
with that data.When you call those methods, you get a new download task. As soon as you resume that task, the session calls its delegate’s URLSession:downloadTask:didResumeAtOffset:expectedTotalBytes: method with that new task to indicate that the download is resumed.
5. URLSessionStreamDelegate
optional public func urlSession(_ session: URLSession,
readClosedFor streamTask: URLSessionStreamTask)
Tells the delegate that the read side of the underlying socket has been closed.
This method may be called even if no reads are currently in progress. This method does not indicate that the stream reached end-of-file (EOF), such that no more data can be read.
Indiciates that the read side of a connection has been closed. Any
outstanding reads complete, but future reads will immediately fail.
This may be sent even when no reads are in progress. However, when
this delegate message is received, there may still be bytes
available. You only know that no more bytes are available when you
are able to read until EOF.
optional public func urlSession(_ session: URLSession,
writeClosedFor streamTask: URLSessionStreamTask)
Tells the delegate that the write side of the underlying socket has been closed.
This method may be called even if no writes are currently in progress
Indiciates that the write side of a connection has been closed.
Any outstanding writes complete, but future writes will immediately
fail.
optional public func urlSession(_ session: URLSession,
betterRouteDiscoveredFor streamTask: URLSessionStreamTask)
Tells the delegate that a better route to the host has been detected for the stream.
This method is called when the URL loading system determines that a better route to the endpoint host is available. For example, this method may be called when a Wi-Fi interface becomes available.
You should consider completing pending work and creating a new stream task in order to take advantage of better routes when they become available.
optional public func urlSession(_ session: URLSession,
streamTask: URLSessionStreamTask,
didBecome inputStream: InputStream,
outputStream: OutputStream)
Tells the delegate that the stream task has been completed as a result of the stream task calling the captureStreams() method.
This delegate method will only be called after all enqueued reads and writes for the stream task have been completed.