Alamofire download file

Alamofire download file

alamofire download file

upload: Upload files with multipart, stream, file or data methods. Alamofire.​download: Download files or resume a download. In older version of Alamofire. This is how I download file let destinationPath = Alamofire.Request.suggestedDownloadDestination(directory. To download files on other platforms, see the Download File Destination section. Alamofire.download("https://httpbin.org/image/png").responseData { response in if. alamofire download file

Alamofire download file - remarkable

hilljh82/Alamofire

Alamofire is an HTTP networking library written in Swift.

  • Features
  • Component Libraries
  • Requirements
  • Migration Guides
  • Communication
  • Installation
  • Usage
  • Advanced Usage
  • Open Radars
  • FAQ
  • Credits
  • Donations
  • License

Features

  • [x] Chainable Request / Response Methods
  • [x] URL / JSON / plist Parameter Encoding
  • [x] Upload File / Data / Stream / MultipartFormData
  • [x] Download File using Request or Resume Data
  • [x] Authentication with URLCredential
  • [x] HTTP Response Validation
  • [x] Upload and Download Progress Closures with Progress
  • [x] cURL Command Output
  • [x] Dynamically Adapt and Retry Requests
  • [x] TLS Certificate and Public Key Pinning
  • [x] Network Reachability
  • [x] Comprehensive Unit and Integration Test Coverage
  • [x] Complete Documentation

Component Libraries

In order to keep Alamofire focused specifically on core networking implementations, additional component libraries have been created by the Alamofire Software Foundation to bring additional functionality to the Alamofire ecosystem.

  • AlamofireImage - An image library including image response serializers, and extensions, custom image filters, an auto-purging in-memory cache and a priority-based image downloading system.
  • AlamofireNetworkActivityIndicator - Controls the visibility of the network activity indicator on iOS using Alamofire. It contains configurable delay timers to help mitigate flicker and can support instances not managed by Alamofire.

Requirements

  • iOS 8.0+ / macOS 10.10+ / tvOS 9.0+ / watchOS 2.0+
  • Xcode 8.1+
  • Swift 3.0+

Migration Guides

Communication

  • If you need help, use Stack Overflow. (Tag 'alamofire')
  • If you'd like to ask a general question, use Stack Overflow.
  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you want to contribute, submit a pull request.

Installation

CocoaPods

CocoaPods is a dependency manager for Cocoa projects. You can install it with the following command:

CocoaPods 1.1.0+ is required to build Alamofire 4.0.0+.

To integrate Alamofire into your Xcode project using CocoaPods, specify it in your :

Then, run the following command:

Carthage

Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks.

You can install Carthage with Homebrew using the following command:

To integrate Alamofire into your Xcode project using Carthage, specify it in your :

Run to build the framework and drag the built into your Xcode project.

Swift Package Manager

The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the compiler. It is in early development, but Alamofire does support its use on supported platforms.

Once you have your Swift package set up, adding Alamofire as a dependency is as easy as adding it to the value of your .

Manually

If you prefer not to use either of the aforementioned dependency managers, you can integrate Alamofire into your project manually.

Embedded Framework

  • Open up Terminal, into your top-level project directory, and run the following command "if" your project is not initialized as a git repository:

  • Add Alamofire as a git submodule by running the following command:

  • Open the new folder, and drag the into the Project Navigator of your application's Xcode project.

    It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter.

  • Select the in the Project Navigator and verify the deployment target matches that of your application target.
  • Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.
  • In the tab bar at the top of that window, open the "General" panel.
  • Click on the button under the "Embedded Binaries" section.
  • You will see two different folders each with two different versions of the nested inside a folder.

    It does not matter which folder you choose from, but it does matter whether you choose the top or bottom .

  • Select the top for iOS and the bottom one for OS X.

    You can verify which one you selected by inspecting the build log for your project. The build target for will be listed as either , , or .

  • And that's it!

    The is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.


Usage

Making a Request

Response Handling

Handling the of a made in Alamofire involves chaining a response handler onto the .

In the above example, the handler is appended to the to be executed once the is complete. Rather than blocking execution to wait for a response from the server, a callback in the form of a closure is specified to handle the response once it's received. The result of a request is only available inside the scope of a response closure. Any execution contingent on the response or data received from the server must be done within a response closure.

Networking in Alamofire is done asynchronously. Asynchronous programming may be a source of frustration to programmers unfamiliar with the concept, but there are very good reasons for doing it this way.

Alamofire contains five different response handlers by default including:

None of the response handlers perform any validation of the it gets back from the server.

For example, response status codes in the and ranges do NOT automatically trigger an . Alamofire uses Response Validation method chaining to achieve this.

Response Handler

The handler does NOT evaluate any of the response data. It merely forwards on all information directly from the URL session delegate. It is the Alamofire equivalent of using to execute a .

We strongly encourage you to leverage the other response serializers taking advantage of and types.

Response Data Handler

The handler uses the (the object that serializes the server data into some other type) to extract the returned by the server. If no errors occur and is returned, the response will be a and the will be of type .

Response String Handler

The handler uses the to convert the returned by the server into a with the specified encoding. If no errors occur and the server data is successfully serialized into a , the response will be a and the will be of type .

If no encoding is specified, Alamofire will use the text encoding specified in the from the server. If the text encoding cannot be determined by the server response, it defaults to .

Response JSON Handler

The handler uses the to convert the returned by the server into an type using the specified . If no errors occur and the server data is successfully serialized into a JSON object, the response will be a and the will be of type .

All JSON serialization is handled by the API in the framework.

Chained Response Handlers

Response handlers can even be chained:

It is important to note that using multiple response handlers on the same requires the server data to be serialized multiple times. Once for each response handler.

Response Handler Queue

Response handlers by default are executed on the main dispatch queue. However, a custom dispatch queue can be provided instead.

Response Validation

By default, Alamofire treats any completed request to be successful, regardless of the content of the response. Calling before a response handler causes an error to be generated if the response had an unacceptable status code or MIME type.

Manual Validation

Automatic Validation

Automatically validates status code within range, and that the header of the response matches the header of the request, if one is provided.

Response Caching

Response Caching is handled on the system framework level by . It provides a composite in-memory and on-disk cache and lets you manipulate the sizes of both the in-memory and on-disk portions.

By default, Alamofire leverages the shared . In order to customize it, see the Session Manager Configurations section.

HTTP Methods

The enumeration lists the HTTP methods defined in RFC 7231 §4.3:

These values can be passed as the argument to the API:

The method parameter defaults to .

Parameter Encoding

Alamofire supports three types of parameter encoding including: , and . It can also support any custom encoding that conforms to the protocol.

URL Encoding

The type creates a url-encoded query string to be set as or appended to any existing URL query string or set as the HTTP body of the URL request. Whether the query string is set or appended to any existing URL query string or set as the HTTP body depends on the of the encoding. The enumeration has three cases:

  • - Applies encoded query string result to existing query string for , and requests and sets as the HTTP body for requests with any other HTTP method.
  • - Sets or appends encoded query string result to existing query string.
  • - Sets encoded query string result as the HTTP body of the URL request.

The HTTP header field of an encoded request with HTTP body is set to . Since there is no published specification for how to encode collection types, the convention of appending to the key for array values (), and appending the key surrounded by square brackets for nested dictionary values ().

GET Request With URL-Encoded Parameters
POST Request With URL-Encoded Parameters

JSON Encoding

The type creates a JSON representation of the parameters object, which is set as the HTTP body of the request. The HTTP header field of an encoded request is set to .

POST Request with JSON-Encoded Parameters

Property List Encoding

The uses to create a plist representation of the parameters object, according to the associated format and write options values, which is set as the body of the request. The HTTP header field of an encoded request is set to .

Custom Encoding

In the event that the provided types do not meet your needs, you can create your own custom encoding. Here's a quick example of how you could build a custom type to encode a JSON string array onto a .

Manual Parameter Encoding of a URLRequest

The APIs can be used outside of making network requests.

HTTP Headers

Adding a custom HTTP header to a is supported directly in the global method. This makes it easy to attach HTTP headers to a that can be constantly changing.

For HTTP headers that do not change, it is recommended to set them on the so they are automatically applied to any created by the underlying . For more information, see the Session Manager Configurations section.

The default Alamofire provides a default set of headers for every . These include:

  • , which defaults to , per RFC 7230 §4.2.3.
  • , which defaults to up to the top 6 preferred languages on the system, formatted like , per RFC 7231 §5.3.5.
  • , which contains versioning information about the current app. For example: , per RFC 7231 §5.5.3.

If you need to customize these headers, a custom should be created, the property updated and the configuration applied to a new instance.

Authentication

Authentication is handled on the system framework level by and .

Supported Authentication Schemes

HTTP Basic Authentication

The method on a will automatically provide a to a when appropriate:

Depending upon your server implementation, an header may also be appropriate:

Authentication with URLCredential

It is important to note that when using a for authentication, the underlying will actually end up making two requests if a challenge is issued by the server. The first request will not include the credential which "may" trigger a challenge from the server. The challenge is then received by Alamofire, the credential is appended and the request is retried by the underlying .

Downloading Data to a File

Requests made in Alamofire that fetch data from a server can download the data in-memory or on-disk. The APIs used in all the examples so far always downloads the server data in-memory. This is great for smaller payloads because it's more efficient, but really bad for larger payloads because the download could run your entire application out-of-memory. Because of this, you can also use the APIs to download the server data to a temporary file on-disk.

This will only work on as is. Other platforms don't allow access to the filesystem outside of your app's sandbox. To download files on other platforms, see the Download File Destination section.

The APIs should also be used if you need to download data while your app is in the background. For more information, please see the Session Manager Configurations section.

Download File Destination

You can also provide a closure to move the file from the temporary directory to a final destination. Before the temporary file is actually moved to the , the specified in the closure will be executed. The two currently supported are:

  • - Creates intermediate directories for the destination URL if specified.
  • - Removes a previous file from the destination URL if specified.

You can also use the suggested download destination API.

Download Progress

Many times it can be helpful to report download progress to the user. Any can report download progress using the API.

The API also takes a parameter which defines which the download progress closure should be called on.

Resuming a Download

If a is cancelled or interrupted, the underlying URL session may generate resume data for the active . If this happens, the resume data can be re-used to restart the where it left off. The resume data can be accessed through the download response, then reused when trying to restart the request.

IMPORTANT: On the latest release of all the Apple platforms (iOS 10, macOS 10.12, tvOS 10, watchOS 3), is broken on background URL session configurations. There's an underlying bug in the generation logic where the data is written incorrectly and will always fail to resume the download. For more information about the bug and possible workarounds, please see this Stack Overflow post.

Uploading Data to a Server

When sending relatively small amounts of data to a server using JSON or URL encoded parameters, the APIs are usually sufficient. If you need to send much larger amounts of data from a file URL or an , then the APIs are what you want to use.

The APIs should also be used if you need to upload data while your app is in the background. For more information, please see the Session Manager Configurations section.

Uploading Data

Uploading a File

Uploading Multipart Form Data

Upload Progress

While your user is waiting for their upload to complete, sometimes it can be handy to show the progress of the upload to the user. Any can report both upload progress and download progress of the response data using the and APIs.

Statistical Metrics

Timeline

Alamofire collects timings throughout the lifecycle of a and creates a object exposed as a property on all response types.

The above reports the following info:

  • : 0.428 seconds
  • : 0.428 seconds
  • : 0.001 seconds
  • : 0.429 seconds

URL Session Task Metrics

In iOS and tvOS 10 and macOS 10.12, Apple introduced the new URLSessionTaskMetrics APIs. The task metrics encapsulate some fantastic statistical information about the request and response execution. The API is very similar to the , but provides many more statistics that Alamofire doesn't have access to compute. The metrics can be accessed through any response type.

It's important to note that these APIs are only available on iOS and tvOS 10 and macOS 10.12. Therefore, depending on your deployment target, you may need to use these inside availability checks:

cURL Command Output

Debugging platform issues can be frustrating. Thankfully, Alamofire objects conform to both the and protocols to provide some VERY helpful debugging tools.

CustomStringConvertible

CustomDebugStringConvertible

Outputs:


Advanced Usage

Alamofire is built on and the Foundation URL Loading System. To make the most of this framework, it is recommended that you be familiar with the concepts and capabilities of the underlying networking stack.

Recommended Reading

Session Manager

Top-level convenience methods like use a default instance of , which is configured with the default .

As such, the following two statements are equivalent:

Applications can create session managers for background and ephemeral sessions, as well as new managers that customize the default session configuration, such as for default headers () or timeout interval ().

Creating a Session Manager with Default Configuration

Creating a Session Manager with Background Configuration

Creating a Session Manager with Ephemeral Configuration

Modifying the Session Configuration

This is not recommended for or headers. Instead, use the parameter in the top-level APIs, and , respectively.

Session Delegate

By default, an Alamofire instance creates a object to handle all the various types of delegate callbacks that are generated by the underlying . The implementations of each delegate method handle the most common use cases for these types of calls abstracting the complexity away from the top-level APIs. However, advanced users may find the need to override the default functionality for various reasons.

Override Closures

The first way to customize the behavior is through the use of the override closures. Each closure gives you the ability to override the implementation of the matching API, yet still use the default implementation for all other APIs. This makes it easy to customize subsets of the delegate functionality. Here are a few examples of some of the override closures available:

The following is a short example of how to use the to avoid following redirects to any domains.

Subclassing

Another way to override the default implementation of the is to subclass it. Subclassing allows you completely customize the behavior of the API or to create a proxy for the API and still use the default implementation. Creating a proxy allows you to log events, emit notifications, provide pre and post hook implementations, etc. Here's a quick example of subclassing the and logging a message when a redirect occurs.

Generally speaking, either the default implementation or the override closures should provide the necessary functionality required. Subclassing should only be used as a last resort.

It is important to keep in mind that the are initialized and destroyed in the default implementation. Be careful when subclassing to not introduce memory leaks.

Request

The result of a , , or methods are a , , and which all inherit from . All instances are always created by an owning session manager, and never initialized directly.

Each subclass has specialized methods such as , , and that each return the caller instance in order to facilitate method chaining.

Requests can be suspended, resumed and cancelled:

  • : Suspends the underlying task and dispatch queue.
  • : Resumes the underlying task and dispatch queue. If the owning manager does not have set to , the request must call in order to start.
  • : Cancels the underlying task, producing an error that is passed to any registered response handlers.

Routing Requests

As apps grow in size, it's important to adopt common patterns as you build out your network stack. An important part of that design is how to route your requests. The Alamofire and protocols along with the design pattern are here to help.

URLConvertible

Types adopting the protocol can be used to construct URLs, which are then used to construct URL requests internally. , , and conform to by default, allowing any of them to be passed as parameters to the , , and methods:

Applications interacting with web applications in a significant manner are encouraged to have custom types conform to as a convenient way to map domain-specific models to server resources.

Type-Safe Routing

URLRequestConvertible

Types adopting the protocol can be used to construct URL requests. conforms to by default, allowing it to be passed into , , and methods directly (this is the recommended way to specify custom HTTP body for individual requests):

Applications interacting with web applications in a significant manner are encouraged to have custom types conform to as a way to ensure consistency of requested endpoints. Such an approach can be used to abstract away server-side inconsistencies and provide type-safe routing, as well as manage authentication credentials and other state.

API Parameter Abstraction
CRUD & Authorization

Adapting and Retrying Requests

Most web services these days are behind some sort of authentication system. One of the more common ones today is OAuth. This generally involves generating an access token authorizing your application or user to call the various supported web services. While creating these initial access tokens can be laborsome, it can be even more complicated when your access token expires and you need to fetch a new one. There are many thread-safety issues that need to be considered.

The and protocols were created to make it much easier to create a thread-safe authentication system for a specific set of web services.

RequestAdapter

The protocol allows each made on a to be inspected and adapted before being created. One very specific way to use an adapter is to append an header to requests behind a certain type of authentication.

RequestRetrier

The protocol allows a that encountered an while being executed to be retried. When using both the and protocols together, you can create credential refresh systems for OAuth1, OAuth2, Basic Auth and even exponential backoff retry policies. The possibilities are endless. Here's an example of how you could implement a refresh flow for OAuth2 access tokens.

DISCLAIMER: This is NOT a global solution. It is merely an example demonstrating how one could use the in conjunction with the to create a thread-safe refresh system.

To reiterate, do NOT copy this sample code and drop it into a production application. This is merely an example. Each authentication system must be tailored to a particular platform and authentication type.

Источник: [https://torrent-igruha.org/3551-portal.html]

Alamofire download file

0 thoughts to “Alamofire download file”

Leave a Reply

Your email address will not be published. Required fields are marked *