iOS Web Development (8) Implementation of File download

Source: Internet
Author: User

This article describes the file download, which includes the following:

    1. The basic principle of the original ecology of segmented download

    2. Download tasks for Nsurlsession

    3. Download using afnetworking

    4. Download tasks frequently encountered situation



    • The basic principle of the original ecology of segmented download

File download often takes a long time, the implementation of segmented download is the precondition to achieve the breakpoint download

The following two issues need to be addressed in implementing a multipart download

Issue 1: Before downloading, you need to know the length of the file

Issue 2: One paragraph of each request to download a file


    • Get file length for problem 1:head request

The head request only gets the sound message, not the actual data of the resource

Typically used to obtain file length and to detect changes in server-side resources

The Nsurlresponse property of the response object exceptedcontentlength that is the length of the file

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/7C/B5/wKioL1bWoZDDQWAIAAE5GfOrWAQ024.png "title=" screen shot 2016-03-02 pm 4.15.31.png "alt=" Wkiol1bwozddqwaiaae5gforwaq024.png "/>


    • Segmented download for Issue 2: request Header parameter Range

The HTTP protocol specifies that the range parameter in the request header is used to request a piece of data

Such as:

bytes=0-499 from 0 to 499 of the first 500 bytes

bytes=500-999 from 500 to 999 of the second 500 bytes

bytes=500-All bytes since 500 bytes

Bytes=-500 last 500 bytes

bytes=500-599,800-899 specify several ranges at the same time

That is, a multipart download, which is sending multiple requests per request, sets the Range field

The following code completes a multipart download of a file:

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M02/7C/B7/wKiom1bWoTfAHBNxAAF-KcXnyok764.png "title=" screen shot 2016-03-02 pm 4.16.01.png "alt=" Wkiom1bwotfahbnxaaf-kcxnyok764.png "/>

The following code, complete a download of the file:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/7C/B5/wKioL1bWocazzP11AAJvcMzPzoI268.png "title=" screen shot 2016-03-02 pm 4.16.25.png "alt=" Wkiol1bwocazzp11aajvcmzpzoi268.png "/>

When using asynchronous downloads, you should use proxies, notifications, and blocks to perform the downloaded processing action.


    • Download tasks for Nsurlsession

To create a download task:

-(Nsurlsessiondownloadtask *) Downloadtaskwithurl: (nsurl*) url-(Nsurlsessiondownloadtask *) DownloadTaskWithURL: ( nsurl*) URL Completionhandler: (void (^) (Nsurl *location, Nsurlresponse *response, Nserror *error)) completionhandler-( Nsurlsessiondownloadtask *) Downloadtaskwithrequest: (Nsurlrequest *) request-(Nsurlsessiondownloadtask *) Downloadtaskwithrequest: (nsurlrequest *) Request Completionhandler: (void (^) (nsurl*location, Nsurlresponse *response , Nserror*error)) Completionhandler

Nsurlsession perform download task-related agent methods:

Periodic invocation, parameters describe the progress of the download-(void) Urlsession: (Nsurlsession *) session Downloadtask: (nsurlsessiondownloadtask*) Downloadtask didwritedata: (int64_t) Byteswritten Totalbyteswritten: (int64_t) Totalbyteswritten Totalbytesexpectedtowrite: (int64_t) totalbytesexpectedtowrite//called when download is complete-(void) Urlsession: (Nsurlsession *) session Downloadtask: (nsurlsessiondownloadtask*) downloadtask didfinishdownloadingtourl: (Nsurl *) location


Example Description:

1) Create the Nsurlsession object and specify the proxy

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7C/B5/wKioL1bWo4mAL7M4AAFAbCcFIH0809.png "title=" screen shot 2016-03-02 pm 4.23.56.png "width=" 649 "height=" 192 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:649px;height:192px; " alt= "Wkiol1bwo4mal7m4aafabccfih0809.png"/>

2) Create a download task and start

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7C/B7/wKiom1bWo2fiTme3AACUUwbMSo0923.png "title=" screen shot 2016-03-02 pm 4.25.27.png "width=" 551 "height=" "border=" 0 "hspace=" 0 "vspace=" 0 "style=" WIDTH:551PX;HEIGHT:76PX; " alt= "Wkiom1bwo2fitme3aacuuwbmso0923.png"/>

3) The Proxy method to complete the download: You should move the downloaded file to the specified directory and rename it

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M01/7C/B7/wKiom1bWpASyXcGxAAHfU3-t2JU148.png "title=" screen shot 2016-03-02 pm 4.27.15.png "width=" 651 "height=" 307 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" WIDTH:651PX;HEIGHT:307PX; " alt= "Wkiom1bwpasyxcgxaahfu3-t2ju148.png"/>

4) To implement the download Progress monitoring Agent method:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M00/7C/B7/wKiom1bWpDmjYRU7AAECSQAHmt8347.png "title=" screen shot 2016-03-02 pm 4.28.56.png "width=" 651 "height=" 143 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" WIDTH:651PX;HEIGHT:143PX; " alt= "Wkiom1bwpdmjyru7aaecsqahmt8347.png"/>



    • Download Pause/Resume Implementation

Nsurlsessiondownloadtask Method of suspension:

-(void) Cancelbyproducingresumedata: (void (^) (NSData *resumedata)) Completionhandler

Parameter Resumedata: Describes breakpoint information

Nsurlsession Create a download task with breakpoint information:

-(Nsurlsessiondownloadtask *) Downloadtaskwithresumedata: (NSData *) resumedata-(Nsurlsessiondownloadtask *) Downloadtaskwithresumedata: (NSData *) Resumedatacompletionhandler: (void (^) (Nsurl *location, Nsurlresponse *response , Nserror*error)) Completionhandler

Related Agent methods:

-(void) Urlsession: (Nsurlsession *) session Downloadtask: (nsurlsessiondownloadtask*) Downloadtask Didresumeatoffset :(int64_t) Fileoffset expectedtotalbytes: (int64_t) expectedtotalbytes


Example Description:

1) Download Pause

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M01/7C/B7/wKiom1bWpKTi9-DmAADA4m066O4960.png "title=" screen shot 2016-03-02 pm 4.30.43.png "width=" 649 "height=" "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:649px;height:110px; " alt= "Wkiom1bwpkti9-dmaada4m066o4960.png"/>

2) Download continue

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7C/B6/wKioL1bWpUHjY15XAAE2ycLRZM0383.png "title=" screen shot 2016-03-02 pm 4.31.16.png "width=" 651 "height=" 242 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:651px;height:242px; " alt= "Wkiol1bwpuhjy15xaae2yclrzm0383.png"/>

3) Proxy method for continuing the download of breakpoints

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/7C/B7/wKiom1bWpRLRPB3eAADY_DRJ2eQ048.png "title=" screen shot 2016-03-02 pm 4.32.26.png "width=" 648 "height=" 104 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" WIDTH:648PX;HEIGHT:104PX; " alt= "Wkiom1bwprlrpb3eaady_drj2eq048.png"/>




    • Download using afnetworking

Download using afnetworking, essentially creating a Nsurlsessiondownloadtask object

Just encapsulates the proxy method into the Afurlsession object and uses the block to specify the behavior

Afurlsessionmanager Creating a download task

//  create download task based on request Object-  (nsurlsessiondownloadtask *) Downloadtaskwithrequest: (nsurlrequest *) request progress: (nsprogress *__nullable __ autoreleasing *__nullable) Progress destination: (nullable nsurl * ( ^ )   (  NSURL *targetPath , NSURLResponse *response ) destination  Completionhandler: (nullable void  ( ^ )   ( nsurlresponse *response ,  NSURL *filePath , NSError *error ) Completionhandler 
Create love download task based on breakpoint information-(Nsurlsessiondownloadtask *) Downloadtaskwithresumedata: (NSData *) resumedata progress: (Nsprogress * __nullable __autoreleasing *__nullable) Progress destination: (Nullable Nsurl * (^) (Nsurl *targetpath, Nsurlresponse *re sponse)) Destination Completionhandler: (Nullable Void (^) (Nsurlresponse *response, Nsurl *filepath, Nserror *error) ) Completionhandler

Parameter destination: The block is used to specify the path to get the file after download

Parameter Completionhandler: The block executes when the download task is completed

Including when a task is paused (cancelbyproducingresumedata)

Progress: Non-null, returns a Nsprogress object that describes the download progress


Example Description:

1) Create the Nsurlsession object and specify the proxy

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7C/B5/wKioL1bWo4mAL7M4AAFAbCcFIH0809.png "title=" screen shot 2016-03-02 pm 4.23.56.png "width=" 649 "height=" 192 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:649px;height:192px; " alt= "Wkiol1bwo4mal7m4aafabccfih0809.png"/>

2) Download completed block Package 1: should return the final storage URL of the downloaded file

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/7C/B7/wKiom1bWpivi1NPMAAEjV2IX4r8848.png "title=" screen shot 2016-03-02 pm 4.37.13.png "width=" 650 "height=" 159 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" WIDTH:650PX;HEIGHT:159PX; " alt= "Wkiom1bwpivi1npmaaejv2ix4r8848.png"/>

3) Task complete block package: including processing in case of error, prompt under successful request, etc.

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/7C/B7/wKiom1bWpoPS0ceoAAKAEHfXtRs375.png "title=" screen shot 2016-03-02 pm 4.38.33.png "width=" 650 "height=" 445 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:650px;height:445px; " alt= "Wkiom1bwpops0ceoaakaehfxtrs375.png"/>

4) Download Task creation start/continue

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M02/7C/B6/wKioL1bWp0iA-IEdAAHBNfz1ZYM461.png "title=" screen shot 2016-03-02 pm 4.39.56.png "width=" 651 "height=" 278 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:651px;height:278px; " alt= "Wkiol1bwp0ia-iedaahbnfz1zym461.png"/>

5) Pause for download task

650) this.width=650; "src=" Http://s2.51cto.com/wyfs02/M00/7C/B7/wKiom1bWpv7BGuMyAADAFcmxL_0429.png "title=" screen shot 2016-03-02 pm 4.40.40.png "width=" 651 "height=" 108 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:651px;height:108px; " alt= "Wkiom1bwpv7bgumyaadafcmxl_0429.png"/>



    • Use nsprogress to monitor download progress

In the above code, there is a parameter nsprogress type, passed NULL, this parameter is the AFN framework to listen to the download progress

Nsprogress introduced in iOS7.0, using the Observer pattern

Notifies all of its observers when its Fractioncompleted property value changes

Example Description:

1) Download Task creation start/continue

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M02/7C/B7/wKiom1bWp-nDym78AAJIMvRsxC0345.png "title=" screen shot 2016-03-02 pm 4.44.33.png "width=" 649 "height=" 349 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" WIDTH:649PX;HEIGHT:349PX; " alt= "Wkiom1bwp-ndym78aajimvrsxc0345.png"/>

2) Response method of KVO

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7C/B6/wKioL1bWqMfDqzdTAADYvAfM5GY725.png "title=" screen shot 2016-03-02 pm 4.46.22.png "width=" 648 "height=" 145 "border=" 0 "hspace=" 0 "vspace=" 0 "style=" width:648px;height:145px; " alt= "Wkiol1bwqmfdqzdtaadyvafm5gy725.png"/>

Where Self.progressview is a custom view object to display the progress of the download

    • Download tasks frequently encountered situation

Status one: How to save the download status when the program exits

Download the Task management class and register the responder as the following UIApplication object notification

uiapplicationdidenterbackgroundnotification

uiapplicationwillterminatenotification

Response method implementation: Pauses all download tasks and saves breakpoint information to local operations

The action to read the breakpoint information from the local in response to the following notification

Uiapplicationwillenterforegroundnotification

Or, when the download task management object is created, the operation to read the breakpoint information from the local

Condition two: When downloading from a breakpoint, what should I do if the file on the server changes or is deleted?

You can send a head request before continuing the download from a breakpoint to determine if the file exists, and if the length of the file has changed.


This article is from the "Ammon" blog, make sure to keep this source http://annmeng.blog.51cto.com/3321237/1746811

iOS Web Development (8) Implementation of File download

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.