Summarize the resumable upload tasks in iOS development.

Source: Internet
Author: User
Tags tmp file tmp folder

Summarize the resumable upload tasks in iOS development.
Overview

Resumable upload re-downloads or uploads data from where the file is interrupted, rather than from where the file is interrupted. When downloading large files, if the resumable data transfer function is not implemented, the object will be downloaded from the beginning every time an exception occurs or the user takes the initiative to suspend the download, which is a waste of time. Therefore, when downloading large files in a project, the resumable upload function is essential. Of course, there is a special case for resumable data transfer, that is, our application is killed by the user or the application crash. To achieve resumable data transfer after the application is restarted, this is the problem we will solve.

Principle of resumable Data Transfer

The server must support resumable data transfer. Currently, the two most common methods are as follows:FTPAndHTTP.

Next we will briefly introduce the principle of HTTP resumable upload.

HTTP

HTTP enables resumable upload. Resumable upload mainly depends on the Range defined in the HTTP header. The application can resume the download of a failed resource through an HTTP request. Of course, not all wind servers support Range, so it is not our consideration that Range is not supported. Range is calculated in bytes, and the number of bytes at the end of the request is not equal to the number of bytes, because the requester does not necessarily know the size of the resource.
This keyword can be used to tell the server what data is returned to me.
For example:
Bytes = 500-999 indicates 500th-999th bytes
Bytes = 500-indicates all bytes from 500th bytes
Then, We splice the data returned by the server to the end of the file to achieve resumable data transfer.

Resumable upload analysis-AFHTTPRequestOperation

After learning about the principle of resumable upload, we can start to implement resumable upload in iOS. Since all the projects I have access to are deployed on the HTTP server, the resumable data transfer function is also implemented based on HTTP. First, let's start with the simplest implementation provided by the third-party magic AFNetworking. See the detailed code below:

// 1. specify the URL of the downloaded file: URLString // 2. get the path of the saved file filePath // 3. obtain NSURLRquest NSString * URLString = @ ""; NSString * filePath = @ ""; NSURLRequest * request = [NSURLRequest requestWithURL: [NSURL URLWithString: URLString]; signed long downloadBytes = 0; ([[NSFileManager defaultManager] fileExistsAtPath: filePath]) {// 3.1 If you have downloaded it before, then add Range in the HTTP Request Header // get the size of the downloaded file downloadedBytes = [self fileSizeForPath: filePath]; // verify whether the file has been downloaded if (downloadedBytes> 0) {// If downloaded, modify the Range NSMutableURLRequest * mutableURLRequest = [request mutableCopy] in the HTTP header during resumable upload; NSString * requestRange = [NSString stringWithFormat: @ "bytes = % llu-", downloadedBytes]; [mutableURLRequest setValue: requestRange forHTTPHeaderField: @ "Range"]; request = mutableURLRequest ;}} // 4 Create AFHTTPRequestOperation * operation = [[AFHTTPRequestOperation alloc] initWithRequest: request]; // 5 set the operation output stream and save it to operation in the file in step 1. outputStream = [NSOutputStream outputStreamToFileAtPath: filePath append: YES]; // 6 sets the download progress processing block [operation setDownloadProgressBlock: ^ (NSUInteger bytesRead, long totalBytesRead, long timeout) {// bytesRead the number of bytes currently read // total number of bytes read by totalBytesRead, including the total size of the totalBytesExpectedToRead file before resumable data transfer}]; // 7 set success and failure to process block [operation failed: ^ (AFHTTPRequestOperation * operation, id responseObject) {} failure: ^ (AFHTTPRequestOperation * operation, NSError * error) {}]; // 8 start operation [operation start];

With the above Code, the resumable upload function is implemented. When the application is restarted or an exception occurs, the download can start based on the downloaded part. The key is to make the downloaded data persistent. Next, let's take a brief look.AFHTTPRequestOperationIs implemented. By viewing the source code, we found thatAFHTTPRequestOperationInherited fromAFURLConnectionOperation, AndAFURLConnectionOperationImplementedNSURLConnectionDataDelegateProtocol.

Process:

As you can see, AFNetworking adopts the method of self-thread step-by-step interface, because a Runloop problem occurs when the asynchronous interface is called directly in the main thread. When the main thread calls[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES]When the request is sent, the listening task will be added to the Runloop in the main thread. We know that the default RunloopMode is NSDefuaultRunloopMode, which indicates that this task will be executed only when the Runloop of the current thread processes NSDefaultRunloopMode. When a user is rolling tableview and scrollview, The Runloop of the main thread is in NSEventTrackingRunloop mode and the NSDefaultRunloopMode task is not executed.

In addition, the DownloadProgressBlock, success, and failure Block must be returned to the main thread for processing because the subthread calls the interface.

Implementation of NSURLConnecttion for resumable Data Transfer

NSURLConnecttion has been abandoned by Apple since 2015, so we will not discuss it too much here. Please note that I am a ellipsis ......

NSURLSessionDataTask

Apple launched a new class in iOS 7NSURLSession, It hasNSURLConnectionAnd more powerful. Therefore, we recommend that you use this class for download and resume. Shows the ing between NSURLConnection and NSURLSession delegate. Therefore, the key is to meet NSURLSessionDataDelegate and NSURLsessionTaskDelegate.

Implementation of File Download and Suspension

When NSURLSessionDownloadTask is used for download, the system will create a download path in the cache folder, with a "CFNetworking" header under the path. tmp file (hereinafter referred to as "download file" to prevent confusion), this is the file we are downloading. When cancelByProducingResumeData: method is called, a data file is obtained. After being formatted using String, it is found to be an XML file, which contains information about. description of some key points of the tmp file, including "Range", "key", and "download file path. the downloaded files originally stored in the download file are moved to the tmp folder directory of the system. when we perform the resume operation again, the downloaded file is moved back to the download folder.

Resumable upload of the program killed

Based on the above analysis, the following conclusions can be drawn:

  • When DownloadTask resumes resumable upload, it searches for the downloaded file based on the "path Key" in the data file, verifies the file, and then performs resumable Upload Based on the "Range" attribute.

  • The download folder stores only the files in the download. Once paused, the files will be moved to the tmp folder.

  • Each paused data file corresponds to the downloaded file.

  • Resumable upload is only related to files in the tmp folder.

Therefore, we can do this by setting a Bool variable to determine whether a download is in progress, and pausing an event every time with a periodic event. Save the data file and copy the downloaded files in the tmp folder to the secure directory (because the tmp folder is said to be cleared at any time ).
When you download the file again, obtain the downloaded file from the secure directory, delete the original file with the same name in the tmp folder, and copy it to the tmp directory, finally, you can use the stored data file to perform the downloadTaskWithResumeData operation again to download the file again.

Link to the original article: Summarize the resumable upload tasks in iOS 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.