SAPURLSession
public class SAPURLSession
This class represents a client that can be used to communicate with an HTTP server. It wraps the native URLSession
.
You have different options to create a SAPURLSession
instance. The simplest way is to initialize it using defaults.
let urlSession = SAPURLSession()
Note: When using the default initializer, the SAPURLSession
initilizes the underlying URLSession
with the following parameters:
- configuration: URLSessionConfiguration.default
- delegate: nil
- delegateQueue: nil
If you need to be informed about URLSession
events, implement the SAPURLSessionDelegate
APIs, and pass this delegate as a parameter.
You can register this delegate also to obtain the backing URLSessionTask
once its initialized.
let urlSession = SAPURLSession(delegate: self)
Once you have created an SAPURLSession
you can use it to exchange messages.
Depending on your use case you can either directly use this session or pass it to other SDK components that require an SAPURLSession
instance for communication.
The SAPURLSession
class exposes methods for sending short requests to the server, and it supports downloading and uploading of large payloads as well.
-
Read-only access to this flag which identifies if the underlying SAPURLSession is valid. By default it is true. This value will be set to false if the SAPURLSession is invalidated.
Declaration
Swift
private(set) public var isValid: Bool { get }
-
The delegate assigned when this object was created.
Declaration
Swift
public var delegate: SAPURLSessionDelegate? { get }
-
The delegate queue assigned when this object was created.
Declaration
Swift
public var delegateQueue: OperationQueue { get }
-
An NSURLSessionConfiguration object defines the behavior and policies to use when uploading and downloading data using an URLSession object.
Declaration
Swift
public var configuration: URLSessionConfiguration { get }
-
The sessionDescription property is available for the developer to provide a descriptive label for the session.
Declaration
Swift
public var sessionDescription: String? { get set }
-
Returns a copy of the registered
SAPURLSessionObserving
instances. Can be used to identify and unregister them from theSAPURLSession
.Declaration
Swift
public var observers: [SAPURLSessionObserving] { get }
-
Creates a session with the specified session configuration, delegate, and operation queue.
Declaration
Swift
public init(configuration: URLSessionConfiguration = URLSessionConfiguration.default, delegate: SAPURLSessionDelegate? = nil, delegateQueue queue: OperationQueue? = nil)
Parameters
configuration
A configuration object that specifies certain behaviors, such as caching policies, timeouts, proxies, pipelining, TLS versions to support, cookie policies, and credential storage. See URLSessionConfiguration for more information.
delegate
A session delegate object that handles requests for authentication and other session-related events. This delegate object is responsible for handling authentication challenges, for making caching decisions, and for handling other session-related events. If nil, the class should be used only with methods that take completion handlers. Important The session object keeps a strong reference to the delegate. When the session is released it calls the invalidateAndCancel() method on the underlying URLSession object.
queue
An operation queue for scheduling the delegate calls and completion handlers. The queue should be a serial queue, in order to ensure the correct ordering of callbacks. If nil, the session creates a serial operation queue for performing all delegate method calls and completion handler calls.
-
-finishTasksAndInvalidate returns immediately and existing tasks will be allowed to run to completion. New tasks may not be created. The session will continue to make delegate callbacks until URLSession:didBecomeInvalidWithError: has been issued.
-finishTasksAndInvalidate and -invalidateAndCancel do not have any effect on the shared session singleton.
When invalidating a background session, it is not safe to create another background session with the same identifier until URLSession:didBecomeInvalidWithError: has been issued.
Declaration
Swift
public func finishTasksAndInvalidate()
-
-invalidateAndCancel acts as -finishTasksAndInvalidate, but issues -cancel to all outstanding tasks for this session. Note task cancellation is subject to the state of the task, and some tasks may have already have completed at the time they are sent -cancel.
Declaration
Swift
public func invalidateAndCancel()
-
Empty all cookies, cache and credential stores, removes disk files, issues -flushWithCompletionHandler:. Invokes completionHandler() on the delegate queue if not nil.
Declaration
Swift
public func reset(completionHandler: @escaping () -> Swift.Void)
-
Flush storage to disk and clear transient network caches. Invokes completionHandler() on the delegate queue if not nil.
Declaration
Swift
public func flush(completionHandler: @escaping () -> Swift.Void)
-
returns a copy of the session with the specified session configuration, delegate, and operation queue.
Declaration
Swift
public func copy(configuration: URLSessionConfiguration = URLSessionConfiguration.default, delegate: SAPURLSessionDelegate? = nil, delegateQueue queue: OperationQueue? = nil) -> SAPURLSession
Parameters
configuration
A configuration object that specifies certain behaviors, such as caching policies, timeouts, proxies, pipelining, TLS versions to support, cookie policies, and credential storage. See URLSessionConfiguration for more information.
delegate
A session delegate object that handles requests for authentication and other session-related events. This delegate object is responsible for handling authentication challenges, for making caching decisions, and for handling other session-related events.
queue
An operation queue for scheduling the delegate calls and completion handlers. The queue should be a serial queue, in order to ensure the correct ordering of callbacks. If nil, operation queue of the source urlsession will be copied to the destination urlsession.
-
Creates a data task with the given request. The request may have a body stream.
Declaration
Swift
public func dataTask(with request: URLRequest) -> SAPURLSessionTask
-
Creates a data task to retrieve the contents of the given URL.
Declaration
Swift
public func dataTask(with url: URL) -> SAPURLSessionTask
-
Creates an upload task with the given request. The body of the request will be created from the file referenced by fileURL.
Declaration
Swift
public func uploadTask(with request: URLRequest, fromFile fileURL: URL) -> SAPURLSessionTask
-
Creates an upload task with the given request. The body of the request is provided from the bodyData.
Declaration
Swift
public func uploadTask(with request: URLRequest, from bodyData: Data) -> SAPURLSessionTask
-
Creates an upload task with the given request. The previously set body stream of the request (if any) is ignored and the URLSession:task:needNewBodyStream: delegate will be called when the body payload is required.
Declaration
Swift
public func uploadTask(withStreamedRequest request: URLRequest) -> SAPURLSessionTask
-
Creates a download task with the given request.
Declaration
Swift
public func downloadTask(with request: URLRequest) -> SAPURLSessionDownloadTask
-
Creates a download task to download the contents of the given URL.
Declaration
Swift
public func downloadTask(with url: URL) -> SAPURLSessionDownloadTask
-
Creates a download task with the resume data. If the download cannot be successfully resumed, URLSession:task:didCompleteWithError: will be called.
Declaration
Swift
public func downloadTask(withResumeData resumeData: Data) -> SAPURLSessionDownloadTask
-
Data task convenience methods. These methods create tasks that bypass the normal delegate calls for response and data delivery, and provide a simple cancelable asynchronous interface to receiving data. Errors will be returned in the NSURLErrorDomain, see
. The delegate, if any, will still be called for authentication challenges. Declaration
Swift
public func dataTask(with request: URLRequest, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SAPURLSessionTask
-
Data task convenience methods. These methods create tasks that bypass the normal delegate calls for response and data delivery, and provide a simple cancelable asynchronous interface to receiving data. Errors will be returned in the NSURLErrorDomain, see
. The delegate, if any, will still be called for authentication challenges. Declaration
Swift
public func dataTask(with url: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SAPURLSessionTask
-
Upload convenience method.
Declaration
Swift
public func uploadTask(with request: URLRequest, fromFile fileURL: URL, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SAPURLSessionTask
-
Upload convenience method.
Declaration
Swift
public func uploadTask(with request: URLRequest, from bodyData: Data, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SAPURLSessionTask
-
Download task convenience methods. When a download successfully completes, the URL will point to a file that must be read or copied during the invocation of the completion routine. The file will be removed automatically.
Declaration
Swift
public func downloadTask(with request: URLRequest, completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> SAPURLSessionDownloadTask
-
Download task convenience methods. When a download successfully completes, the URL will point to a file that must be read or copied during the invocation of the completion routine. The file will be removed automatically
Declaration
Swift
public func downloadTask(with url: URL, completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> SAPURLSessionDownloadTask
-
Download task convenience methods. When a download successfully completes, the URL will point to a file that must be read or copied during the invocation of the completion routine. The file will be removed automatically
Declaration
Swift
public func downloadTask(withResumeData resumeData: Data, completionHandler: @escaping (URL?, URLResponse?, Error?) -> Void) -> SAPURLSessionDownloadTask
-
Creates an upload task with the given request. The body stream can be supplied directly from the provided block. When using this method, tha delegates for response and data handling are not called.
Declaration
Swift
public func uploadTask(withStreamedRequest request: URLRequest, needNewBodyStream: @escaping () -> InputStream?, completionHandler: @escaping (Data?, URLResponse?, Error?) -> Void) -> SAPURLSessionTask
-
Creates a data task with the given request. The response and tha data can be directly accessed with the provided blocks. When using this method, tha delegates for response and data handling are not called.
Declaration
Swift
public func dataTask(with request: URLRequest, receivedResponseHandler: ((URLResponse) -> Void)? = nil, receivedDataHandler: @escaping (Data) -> Void, completionHandler: @escaping (Error?) -> Void) -> SAPURLSessionTask
-
Convenience method to load data using an URLRequest
Declaration
Swift
public func data(for request: URLRequest) async throws -> (Data, URLResponse)
-
Convenience method to load data using an URL
Declaration
Swift
public func data(from url: URL) async throws -> (Data, URLResponse)
-
Convenience method to upload data using an URLRequest from URL
Declaration
Swift
public func upload(for request: URLRequest, fromFile fileURL: URL) async throws -> (Data, URLResponse)
-
Convenience method to upload data using an URLRequest from Data
Declaration
Swift
public func upload(for request: URLRequest, from bodyData: Data) async throws -> (Data, URLResponse)
-
Convenience method to download using an URLRequest
Declaration
Swift
public func download(for request: URLRequest) async throws -> (URL, URLResponse)
-
Convenience method to download using an URL
Declaration
Swift
public func download(from url: URL) async throws -> (URL, URLResponse)
-
Convenience method to resume download
Declaration
Swift
public func download(resumeFrom resumeData: Data) async throws -> (URL, URLResponse)
-
Registers the given observer.
Declaration
Swift
public func register(_ observer: SAPURLSessionObserving)
Parameters
observer
the observer to be registered
-
Unregisters the given observer.
Declaration
Swift
public func unregister(_ observer: SAPURLSessionObserving)
Parameters
observer
the observer to be removed
-
Checks if the given observer is already registered.
Declaration
Swift
public func isRegistered(_ observer: SAPURLSessionObserving) -> Bool
Parameters
observer
the observer to be checked
Return Value
true
if there is a match in the registered observers using the===
operator,false
otherwise
-
Configure the given request. Returns with a new request that contains headers from oberservers.
Declaration
Swift
public func configure(_ request: URLRequest, completionHandler: @escaping (URLRequest?, Error?) -> Void)
Parameters
request
the request that should be configured
completionHandler
closure called on completion
-
Configure the given web view’s cookie storage to contain cookies from the shared cookie storage.
Declaration
Swift
public func configure(_ webView: WKWebView, completionHandler: @escaping (Error?) -> Void)
Parameters
webView
the web view whose cookie storage should be configured
completionHandler
closure called on completion
-
Configure the given WebKit cookie storage to contain cookies from the shared cookie storage.
Declaration
Swift
public func configure(_ cookieStore: WKHTTPCookieStore, completionHandler: @escaping (Error?) -> Void)
Parameters
cookieStore
the WebKit cookie storage that should be configured
completionHandler
closure called on completion
-
Configure the given cookie storage to contain cookies from the shared cookie storage.
Declaration
Swift
public func configure(_ cookieStore: HTTPCookieStorage, completionHandler: @escaping (Error?) -> Void)
Parameters
cookieStore
the cookie storage that should be configured
completionHandler
closure called on completion
-
Reverse function of configure(cookieStore:).
Declaration
Swift
public func close(completionHandler: @escaping () -> Void)
Parameters
completionHandler
closure called on completion
-
The DataTaskPublisher class for SAPURLSession.
See moreDeclaration
Swift
public class DataTaskPublisher : Publisher
-
The DataTaskSubscriber class for SAPURLSession.
See moreDeclaration
Swift
public class DataTaskSubscriber : Subscriber, Cancellable
-
Returns a publisher that wraps a SAPURLSession data task for a given URL request.
Usage Example:
struct User: Codable { let name: String let userID: String } let url = URL(string: "https://example.com/endpoint")! let request = URLRequest(url: url) let urlSession = SAPURLSession() cancellable = urlSession .dataTaskPublisher(for: request) .tryMap() { element -> Data in guard let httpResponse = element.response as? HTTPURLResponse, httpResponse.statusCode == 200 else { throw URLError(.badServerResponse) } return element.data } .decode(type: User.self, decoder: JSONDecoder()) .sink(receiveCompletion: { print ("Received completion: \($0).") }, receiveValue: { user in print ("Received user: \(user).")})
Declaration
Swift
public func dataTaskPublisher(for urlRequest: URLRequest) -> DataTaskPublisher
-
Returns a publisher that wraps a SAPURLSession data task for a given URL.
Declaration
Swift
public func dataTaskPublisher(for url: URL) -> DataTaskPublisher