😊😊😊Alamofire thematic directory. Welcome timely feedback and exchange

  • Alamofire (1) – URLSession prerequisite skill
  • Alamofire (2) — Background download
  • Alamofire (3) — Request
  • Alamofire (4) — Details you need to know
  • Alamofire (5) — Response
  • Alamofire (6) — Multiple form uploads
  • Alamofire (7) — Safety certification
  • Alamofire (8) — Final Chapter (Network Monitoring & Notifications & Downloader Packaging)

Alamofire Directory through train — Harmonious learning, not impatient!


Alamofire is a Swift based network library for iOS and macOS. It provides a more elegant interface on Top of Apple’s basic network architecture to simplify the onerous and frequently used tasks of network requests. Alamofire provides chained request/ Response methods, JSON parameter and response serialization, authentication, and other features. The elegance of Alamofire is that it is written entirely by Swift and inherits no features from its Objective-C version, AFNetworking.

Because of ourAlamofireIs the appleURLSessionThe encapsulation, so exploreAlamofireBefore, let’s seeURLSessionEssential foundation of

The basic format of the request network

URLSession.shared.dataTask(with: url) { (data, response, error) in
    if error == nil {
        print("Request successful"\(String(describing: response))" )
    }
}.resume()
Copy the code
  • URLSession.sharedProvides a shared singleton talk object that provides a reasonable default behavior for creating tasks. Using a shared session gets the contents of the URL into memory in just a few lines of code.
  • dataTaskCreate a network session data task.
  • resumeThe default network task is suspended, and the call executes to start the connection request network:Three handshakes...
  • Requests for results or failures come back to the closure
  • Closures are just a layer of encapsulation, reallyURLSessionThe agent of
  • In fact, in this process, we left out one important thing:URLSessionConfiguration

Second, the URLSessionConfiguration

1. The model

URLSessionConfiguration initialization has three modes:

  • Default: the default mode. This mode is usually sufficient. In default mode, the system creates a persistent cache and stores the certificate in the user’s key string

  • Ephemeral: The system does not have any persistent storage, and all content has the same lifetime as the session. When the session is ephemeral, all content is automatically released.

let configuration1 = URLSessionConfiguration.default
let configuration2 = URLSessionConfiguration.ephemeral
print("Sandbox size:\(String(describing: configuration1.urlCache? .diskCapacity))")
print("Memory size:\(String(describing: configuration1.urlCache? .memoryCapacity))")
print("Sandbox size:\(String(describing: configuration2.urlCache? .diskCapacity))")
print("Memory size:\(String(describing: configuration2.urlCache? .memoryCapacity))"Print result: Sandbox size:Optional(10000000) Memory size:Optional(512000) Sandbox size:Optional(0) Memory size:Optional(512000)
Copy the code
  • backgroundCreate a session that can transfer data in the background even when the APP is closed.backgroundPatterns anddefaultThe pattern is very similar, butbackgroundThe pattern uses a single thread for data transfer.backgroundMode allows tasks to run if the application hangs, exits, or crashes. You can also use identifiers to restore forward. Notice the backgroundSessionBe sure to create a unique identifier so that the next time your APP runs, it can be based onidentifierTo make relevant distinctions.If the user closes the APP,IOS closes all background sessions. In addition, after being forcibly closed by the user, IOS system will not actively wake up the APP, and data transmission will continue only after the user starts the APP next time
// Initializes a background mode session configuration
let configuration = URLSessionConfiguration.background(withIdentifier: self.createID())
// Initializes the session
let session = URLSession.init(configuration: configuration, delegate: self, delegateQueue: OperationQueue.main)
// Pass in the URL to start the download
session.downloadTask(with: url).resume()
Copy the code
  • Initialize a background mode session configuration
  • Initialize thesessionThe session
  • The incomingurlOpen the downloadresume
  • Download progress monitoring
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didWriteData bytesWritten: Int64, totalBytesWritten: Int64, totalBytesExpectedToWrite: Int64)
Copy the code
  • Call back when the download is completeURLSessionDownloadDelegateThe agent
func urlSession(_ session: URLSession, downloadTask: URLSessionDownloadTask, didFinishDownloadingTo location: URL)
Copy the code
Easy to mistake easy to ignore point

The above Settings, can not reach the background download! You also need to set the following two steps

  • Enable the background download permission
// Used to save the completionHandler for the background download
var backgroundSessionCompletionHandler: (() -> Void)?

func application(_ application: UIApplication, handleEventsForBackgroundURLSession identifier: String, completionHandler: @escaping (a) -> Void) {
    self.backgroundSessionCompletionHandler = completionHandler
}
Copy the code
  • Callback System callback that tells the system to update the screen in time
func urlSessionDidFinishEvents(forBackgroundURLSession session: URLSession) {
    print("Background task download back")
    DispatchQueue.main.async {
        guard let appDelegate = UIApplication.shared.delegate as? AppDelegate.let backgroundHandle = appDelegate.backgroundSessionCompletionHandler else { return }
        backgroundHandle()
    }
}
Copy the code

Why is that? It’s Apple’s dad’s call

2. General attributes

  • Identifier:Configures the background session identifier of the object.
  • HttpAdditionalHeaders:Dictionary of additional header files sent with the request.
  • NetworkServiceType:Network service type
  • AllowsCellularAccess:A Boolean value that determines whether a connection should be made over a cellular network.
  • TimeoutIntervalForRequest:Timeout interval to use while waiting for other data.
  • TimeoutIntervalForResource:The maximum amount of time a resource request should allow.
  • SharedContainerIdentifier:The identifier of the shared container of the file in the background URL session should be downloaded.
  • WaitsForConnectivity:A Boolean value indicating whether the session should wait for the connection to become available or fail immediately

3. Set the Cookie policy

  • HttpCookieAcceptPolicy:Decide when to acceptCookiePolicy constant of
  • HttpShouldSetCookies:A Boolean value that determines whether the request should contain data fromCookieStorage ofCookie.
  • HttpCookieStorage:managementcookieSingle object stored (shared instance)
  • HTTPCookie:saidHTTP cookieThe object. It is an immutable object from containscookieProperty in a dictionary

4. Configure security policies

  • TlsMaximumSupportedProtocol:Maximum the client should request when connecting in this sessionThe TLS protocolVersion.
  • TlsMinimumSupportedProtocol:The minimum that should be accepted during the agreement negotiationThe TLS protocol.
  • UrlCredentialStorage:A credential store that provides authentication credentials

5. Set the cache policy

  • UrlCache:Used to provide cached responses to requests in the sessionURLThe cache
  • RequestCachePolicy:A predefined constant that determines when a response is returned from the cache

7. Support background transfer

  • SessionSendsLaunchEvents:A Boolean value indicating whether the application should continue or start in the background when the transfer is complete
  • IsDiscretionary:A Boolean value that determines whether background tasks can be scheduled based on the system’s judgment for optimal performance.

7. Supports user-defined protocols

  • ProtocolClasses:An array of additional protocol subclasses that process the request in the session
  • URLProtocol:aNSURLProtocolObject handling load protocol specificURLThe data. inNSURLProtocolThe class itself is an abstract class that can be specifiedURLThe scheme ofURLDeal with infrastructure. You can support any custom protocols or protocols for your applicationURLScheme creation subclass

8. Supports multipathing TCP

  • MultipathServiceType:Specifies the service type of the multipath TCP connection policy used to transfer data over Wi-Fi and cellular interfaces
  • URLSessionConfiguration. MultipathServiceType:Constant to specify the type of service used by multipath TCP

9. Set the HTTP policy and proxy properties

  • HttpMaximumConnectionsPerHost:The maximum number of simultaneous connections to a given host.
  • HttpShouldUsePipelining:A Boolean value that determines whether the session should use HTTP pipelining
  • ConnectionProxyDictionary:Contains a dictionary of information about the agents used in this session

10. Connection changes are supported

  • WaitsForConnectivity:A Boolean value indicating whether the session should wait for the connection to become available or fail immediately.

Third, NSURLRequestCachePolicy

  • NSURLRequestUseProtocolCachePolicy = 0, :Default cache policy if oneNSCachedURLResponseIf the request does not exist, the data will be fetched from the source. If the request has a cached response, thenURLThe loading system checks the response to determine if it specifies that the content must be reactivated. If the content must be reactivated, a connection is established to the source to see if the content has changed. If the content has not changed, the response returns data from the local cache. If the content changes, the data will be retrieved from the source
  • NSURLRequestReloadIgnoringLocalCacheData = 1:Urls should load source-side data and do not use locally cached data
  • NSURLRequestReloadIgnoringLocalAndRemoteCacheData = 4:Locally cached data, proxies, and other mediations ignore their caches and load source data directly
  • NSURLRequestReloadIgnoringCacheData = NSURLRequestReloadIgnoringLocalCacheData
  • NSURLRequestReturnCacheDataElseLoad = 2:Specifies that stored cached data should be used to respond to a request regardless of its lifetime or expiration. If there is no existing data in the cache to respond to the request, the data is loaded from the source
  • NSURLRequestReturnCacheDataDontLoad = 3:Specifies the cached data that is stored to fulfill the request regardless of lifetime or expiration. If there is no existing data in the cache to respondURLIf the request is loaded, no attempt is made to load data from the source segment and the request is considered to have failed. This constant specifies a behavior similar to offline mode
  • NSURLRequestReloadRevalidatingCacheData = 5:Specifies that cached data is allowed to respond to a request if the stored cached data is validated by the source segment that provides it, otherwise data is loaded from the source segment.

OK, finish! Hopefully, you’ll find out more about URLSession!

Just ask who else is there right now? 45 degrees up in the sky, damn it! My charm with no place to put it!