Nsurlsession Learning notes for swift Web development

Source: Internet
Author: User
Tags closure

First up;

Function:

-Single Task download

-Pause Download Task

-Cancel Download Task

-Breakpoint Download

-Show download Progress and speed

-Multi-tasking download

-Control individual tasks separately

In the current wave of mobile internet, mobile apps are increasingly relying on network communication to interact with data. Today we share the idea of how to use Nsurlsession, the Apple-provided web interface, for file downloads.

Nsurlssession

First introduce the next nsurlsession this interface. Nsurlsession is an Apple introduced on the WWDC2013 to replace its predecessor Nsurlconnection.

Similar to nsurlconnection, except that the same name class nsurlsession,nsurlsession refers to a set of interdependent classes. The nsurlsession includes the same components as before, such as Nsurlrequest, Nsurlcache, and so on. The difference between nsurlsession is that it replaces nsurlconnection with Nsurlsession, Nsurlsessionconfiguration, and 3 sub-classes of Nsurlsessiontask: Nsurlsessiondatatask, Nsurlsessionuploadtask, and Nsurlsessiondownloadtask.


The most straightforward improvement of nsurlsession compared to nsurlconnection is the ability to configure caching, protocol, cookie and certificate policies (credential policies) for each session, and even to share them across applications. This allows the framework's network infrastructure and some applications to work independently, without interfering with each other. Each Nsurlsession object is initialized according to a nsurlsessionconfiguration, and the nsurlsessionconfiguration specifies the policy mentioned above. and a range of new options specifically added to improve mobile device performance.


Another important component of Nsurlsession is the session task, which handles the loading of data and the uploading and downloading of files and data between the client and the server. Nsurlsessiontask and nsurlconnection are similar because they are responsible for loading data, and the main difference is that the task shares the co-delegates of their parent nsurlsession (common delegate).

The nsurlsession supports the following three session modes:

1. Default session Mode: Default mode, based on the disk cache persistence policy, use the certificate saved in user keychain for authentication authorization.

2, instantaneous session mode (ephemeral): Do not store any data on the disk, all data is stored in RAM, when the session ends, the cache data will be emptied.

3, background session mode (background): This mode is similar to the default mode, just move the upload and download to the background processing, need a provide a string to identify the background session.

Nsurlsession also offers a number of configuration options:

Once you have configured the session type, you can get the Nsurlsession object. There are several ways to get objects:

1. Sharedsession gets a session that uses the default, globally shared Cookies,cache, and certificates.

2. Use the constructor to construct a session object for the specified configuration.

3. Use the constructor to construct a specified configuration object and specify proxy and proxy queues.

Once you have finished getting the session object, you should give the object a session task. This is done by setting up a session task object to implement the assignment. In one session, Nsurlsession supports three session tasks:

1. Data Task (Nsurlsessiondatatask)

Use the NSData object to send and receive data. Data tasks can be fragmented to return data, or they can be returned at once by completing the processor. Background sessions are not supported because the data task does not store data to a file.

2. Upload Task (Nsurlsessionuploadtask)

Usually send data in the form of files, support background upload.

3. Task (Nsurlsessiondownloadtask)

Receive data as a file and support background downloads when the program is not running

Once you have the Task object, you can do the following:

Through the brief introduction of Nsurlsession, we should have a simple understanding of the song, and then to introduce how to achieve the beginning of this article to demonstrate all the features of the demo.

Demo explanation

Do some preparatory work first:

Create a struct downloaddata to hold the downloaded data information

Create an agent agreement, and then describe its usefulness

We then started to build our own Downloadtask class, which was used to download the Downloaddata, and to provide functions such as pause task, breakpoint download, cancel task, real-time update download progress and speed, etc.:

Let's start by defining some properties,

which

Proxy is used to trigger the method defined in the previous protocol,

Arrays and timers rush to calculate the download speed,

The task ID is downloaded for easy management of multiple tasks.

And then the constructor,

Through the constructor we will get Downloaddata,id and delegate from the outside.

When this is done, you write the download method,

Once you have set itself as the nsurlsession agent, you need to follow the Nsurlsessiondownloaddelegate protocol in your class and implement its methods.

Here I implement the following methods,

Of course, when constructing a task, you can also use a constructor with a block to pass the action to the task after the task is completed by way of a closure. If you do this, you do not need to set up the proxy in the definition nsurlsession. However, the method of not using the proxy is not able to obtain the real-time information of the download task, so to get the download progress and speed, or should use the Nsurlsession proxy.

If the Completionhandler closure and the Didfinishdownloadingtourl method exist simultaneously, the Completionhandler is prioritized and the Didfinishdownloadingtourl method is ignored.

Here's how to implement real-time speed updates.

Then the method of pausing the task,

It is important to note that the nsdata generated by Cancelbyproducingresumedata does not contain the data that was previously downloaded, but rather the location of the temporary files generated by the download and the information about what progress was downloaded, so it does not occupy a large amount of memory.

After the task is paused, empty the task.

And finally the method of canceling the task,

After emptying the record download information data file, starting the task again will not continue to download from the previously disconnected location.

The above is the entire contents of the Downloadtask class, and finally the creation of a UI call under the Downloadtask, to see how the class in the actual use of the effect.

Ui:

Numbering the controls from 0-5, including 1 progressview,2 Label,3button, and putting them into collection respectively,

Define a taskcollection to hold all the tasks,

Initialize the interface and define 6 Downloadtask:

Add a method to the 3 buttons separately:

Finally implement the Downloadtaskdelegate proxy method for updating the UI:

At this point, the demo part of the explanation is complete.

Summarize

This blog post is mainly my nsurlsession after learning some of the experience, and introduced the next how to achieve through the nsurlsession, multi-task download, breakpoint download and other functions. It is important to note that because Nsurlsession uses the "asynchronous blocking" model, it is necessary to Cheng Che the thread back to the main thread when implementing the Downloadtaskdelegate proxy method to update the UI.

In the next learning Plan, you are ready to study how to control the maximum number of download tasks and download priority, and try to encapsulate all the features.

Nsurlsession Learning notes for swift Web development

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.