Summarize the breakpoints in iOS development to continue the thing.

Source: Internet
Author: User

Overview of the continuation of the preface breakpoint

The continuation of a breakpoint is to restart the download or upload the data from where the file was interrupted, rather than starting with the file from scratch. When downloading large files, if there is no continuation of the breakpoint, then every time the exception or the user's active pause, will be downloaded from the beginning, which is a waste of time has wood. So, when implementing large file downloads in the project, the breakpoint continuation function is essential. Of course, the breakpoint continued to have a special situation, that is, our application chant user kill or apply crash, to achieve the application restart after the breakpoint continuation, this situation is we will solve the problem.

How the breakpoint continues to pass

To implement a breakpoint continuation, the server must be supported. Currently the two most common ways: FTP and HTTP .

The following is a brief introduction to the principle of HTTP breakpoint continuation.

HTTP

Through HTTP, it is very convenient to implement the continuation of the breakpoint. The continuation of a breakpoint is primarily dependent on the range defined by the HTTP header, and the application can resume downloading the resource through an HTTP request that has either returned or partially recovered from the failed resource. Of course not all wind servers support range, so the range is not supported in our consideration. The range is calculated in bytes, and the request is no more than the number of bytes given to me because the requester does not necessarily know the size of the resource.
With this keyword you can tell the server what data to return to me.
Like what:
bytes=500-999 = No. 500-No. 999 byte
bytes=500-represents all bytes from the NO. 500 byte backwards
Then, according to the data returned by the server, the resulting data is stitched to the back of the file, so that the breakpoint can be resumed.

Breakpoint Continuation Analysis-afhttprequestoperation

After understanding the principle of the continuation of the breakpoint, we can start to implement the breakpoint in iOS to continue to pass. Since all of the projects I am currently exposed to are deployed on HTTP servers, the breakpoint continuation feature is also based on the HTTP implementation. First of all, we come to the simplest, third-party magic afnetworking in the implementation provided, see the detailed code below:

 1. Specify the address of the download file URLString//2. Gets the saved file path filepath//3. Get nsurlrquest    nsstring* urlstring = @ "";    nsstring* FilePath = @ "";    nsurlrequest* request = [Nsurlrequest Requestwithurl:[nsurl urlwithstring:urlstring]];    signed Long Long downloadbytes = 0;     ([[Nsfilemanager Defaultmanager] Fileexistsatpath:filepath] {       //3.1 If previously downloaded, the HTTP Request header Join Range        //get size of downloaded file        downloadedbytes = [Self Filesizef Orpath:filepath];        //verify downloaded files        if (downloadedbytes > 0) {      &NBS P    //If downloaded, modify the HTTP header section Range            nsmutableurlrequest *mutableurl When the breakpoint is resumed request = [request mutablecopy];            nsstring *requestrange =            [nsstring Strin gwithformat:@ "bytes=%llu-", Downloadedbytes];            [mutableurlrequest setvalue:requestrange forhttpheaderfield:@ "Range"];            request = mutableurlrequest;        }    }    //4 create afhttprequestoperation    afhttprequestoperatio n *operation    = [[Afhttprequestoperation alloc] initwithrequest:request];     //5 set operation output stream, save in 2nd step file    operation.outputstream = [nsoutputstream                              outputstreamtofileatpath:filepath Append:yes] ;    //6 Set download progress processing block    [operation setdownloadprogressblock:^ (Nsuinteger bytesread,     & nbsp                          ,         &NB Sp;long long totalbytesread, long long Totalbytesexpectedtoread) {       //bytesread the currently read wordNumber of sections        //totalbytesread Total bytes read, including        //Totalbytesexpectedtoread before the breakpoint is resumed  Total File size    }];    //7 settings Success and failure processing block    [operation setcompletionblockwithsuccess:^ (    &N Bsp                          ,         &NB Sp     Afhttprequestoperation *operation                     &NB Sp                         ID responseobject) {   } &N Bsp                              failure:^ (afhttpre Questoperation *operation,                           &NBS P                   Nserror *error) {   }]; &nBsp  //8 start Operation    [operation start];

Using the above code, the breakpoint continuation function is implemented, the application restarts or in the event of an exception, you can start to continue downloading based on the part that has already been downloaded. The key is to persist the downloaded data. The next step AFHTTPRequestOperation is simply to see how it is implemented. By looking at the source code, we found the AFHTTPRequestOperation inheritance AFURLConnectionOperation , and AFURLConnectionOperation realized the NSURLConnectionDataDelegate protocol.

Processing Flow:

As you can see, here the afnetworking takes a self-threading approach to the interface, because invoking the Async interface directly on the main thread will have a runloop problem. When the main thread is called [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES] , the Listener task after the request is added to the runloop in the main thread, we know that Runloopmode defaults to Nsdefuaultrunloopmode, This indicates that the task will only be executed when the runloop of the front-line process Nsdefaultrunloopmode. When the user is scrolling tableview and ScrollView, the main thread's runloop is in Nseventtrackingrunloop mode and will not perform nsdefaultrunloopmode tasks.

The downloadprogressblock,success and failure blocks on this side need to be returned to the main thread for processing, due to the way in which the sub-threads are called interfaces.

Realization of nsurlconnecttion in the actual combat of breakpoint continuation

Nsurlconnecttion This guy has been abandoned by Apple in 2015, so here we don't do too much discussion, please note ah, I am ellipsis ...

Nsurlsessiondatatask

Apple started in IOS7 and launched a new class that has the methods and is NSURLSession NSURLConnection more powerful. So I recommend that you use this class to download and continue to upload. The mapping of the Nsurlconnection and Nsurlsession delegate methods, as shown in. So the key is to meet Nsurlsessiondatadelegate and nsurlsessiontaskdelegate.

Implementation of file download and pause

When using Nsurlsessiondownloadtask to download, the system will create a download path under the cache folder, there will be a "cfnetworking" under the path of a. tmp file (hereinafter referred to as "download file" to prevent confusion), This is the file that we are downloading. And when we call the Cancelbyproducingresumedata: method, we get a data file, formatted with string, and found to be an XML file that contains a description of some key points about the. tmp file, including "Range", " Key "," path to download file "and so on. The downloaded file that existed in the download file is moved to the System TMP folder directory. And when we resume again, the download is moved back to the download folder.

The program is killed the breakpoint continues to pass Resumedata

According to the above analysis, the following conclusions can be obtained:

    • Downloadtask each time a breakpoint is resumed, the data file will be based on "path key" to find the download file, and then check and then according to the "Range" property to continue the breakpoint.

    • The download folder will only be stored in the downloaded file and will be moved to the TMP folder once it is paused.

    • Each paused data file corresponds to the download file one by one.

    • The continuation of a breakpoint is only relevant to files in the TMP folder.

So we can do this by setting up a bool variable to determine if the download is in progress, and to pause it every once in a while with a periodic event. Then save the data file and copy the downloaded file under the TMP folder to the secure directory (because the TMP folder is said to be empty at any time).
When downloading again, first from the security directory to download the file, delete the TMP folder has the same name file, and then copy to the TMP directory, and finally use the saved data file to re-downloadtaskwithresumedata operation, It will be possible to download it again.

Text Link: Summarize the breakpoints in iOS development.

Summarize the breakpoints in iOS development to continue the thing.

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.