IOS-resumable upload and ios-resumable upload

Source: Internet
Author: User

IOS-resumable upload and ios-resumable upload

* Mobile clients are widely used for uploading and downloading when interacting with servers.

* When we download an object, we can pause the download when we click pause. When we click Download, we can continue the download. How can this function be implemented?

* How is the download progress bar displayed?

First, let's briefly describe the principle of resumable download:

* First, determine whether the object to be downloaded exists in the local sandbox.

* If yes, determine the length of the downloaded file.

* If the file length is 500, we should start from 500 when initiating a download request.

* Click "Pause download". The link should be disconnected.

* Click Download again to continue the download based on the length of the downloaded file.

The following code is used to describe the specific implementation:

* Assume that the file to be downloaded is in the server path: http: // localhost: 8080: down/xcode_6.dmg;

* The file to be downloaded is stored in the local sandbox. File Name: xcode. dmg.

* Get the code for saving the file path: (fold)

1-(NSString *) getFilePath2 {3 NSString * documentsPath = alias (NSDocumentDirectory, NSUserDomainMask, YES) [0]; 4 NSString * filePath = [documentsPath stringByAppendingPathComponent: @ "xcode. dmg "]; 5 return filePath; 6}Download file storage path

* Because the downloaded file is large, we need to adopt an asynchronous request network.

* There are four common proxy methods for asynchronous request networks.

* Initiate a network request for download. (The download start point is the last pause point. The method for determining the last pause position is to obtain the file attributes. You can view the file length from the attributes. The request point is the content after the length)

* If you want to obtain the content of a certain byte, you can use:

 

// Bytes = 0-499 content of the first 500 bytes of the request

 

// Bytes = 500-request content after 500 bytes

 

// Bytes = 500-1000 request content within a certain range of resources

 

// Bytes = 0-1,499-500 content between multiple request ranges

* The progress bar indicates the file download progress. You can use the number of bytes of the downloaded file/The total number of bytes of the file.

The following is a specific code segment with detailed notes:

 

# Import <UIKit/UIKit. h> @ interface ViewController: UIViewController <NSURLConnectionDataDelegate> {// progress bar variable, displaying the object download progress IBOutlet UIProgressView * _ progress; // file processing, write the downloaded file to the Local Sandbox NSFileHandle * _ fileHandle; // url connection, click suspend, cancel connection, and click Download to start downloading NSURLConnection * _ connection; // The size of received data long _ receiveSize; // The total size of the file long _ totalSize;} // click the response function-(IBAction) download (id) sender at the download button; // click the pause button and choose response function-(IBAction) pause :( id) sender; @ end.

 

 

-(IBAction) download :( id) sender {// file path NSString * string = @ "http: // localhost: 8080/down/xcode_6.dmg "; // convert the file path to url NSURL * url = [NSURL URLWithString: string]; // create a variable request NSMutableURLRequest * request = [NSMutableURLRequest requestWithURL: url]; // check whether the file exists in the sandbox path. YES indicates that the file has been downloaded. NO indicates that if ([[NSFileManager defamanager manager] fileExistsAtPath: [self getFilePath] = YES) {// Based on the file attributes, obtain the amount of data downloaded previously. NSDictionary * fileDic = [[NSFileManager defaultManager] attributesOfItemAtPath: [self getFilePath] error: nil]; // The object length is the downloaded data size _ receiveSize = [fileDic [NSFileSize] longLongValue]; // set the Range, download the content after Range // bytes = 0-499 the content of the first 500 bytes in the request // bytes = 500-the content after the request is 500 bytes // bytes = 500-1000 content in a specific range in the request resource // bytes = 0-1,499-500 content NSString * bytes = [NSString stringWithFormat: @ "bytes = % lld-", _ receiveSize]; [request setValue: bytes forHTTPHeaderField: @ "Range"];} // initiates an asynchronous request. file comparison method, use asynchronous request _ connection = [NSURLConnection connectionWithRequest: request delegate: self];}-(void) connection :( NSURLConnection *) connection didReceiveResponse :( NSURLResponse *) response {// analyze the response header NSHTTPURLResponse * httpResponse = (NSHTTPURLResponse *) response; // get the response header, which is a dictionary NSDictionary * responseHeader = httpResponse. allHeaderFields; // The total size of the received file is equal to the downloaded data volume, plus the downloaded data volume _ totalSize = _ receiveSize + [responseHeader [@ "Content-Length"] longLongValue]; // create a file management class NSFileManager * fileManager = [NSFileManager defaultManager]; // if the file to be downloaded does not exist in the sandbox, create the file if ([fileManager fileExistsAtPath: [self getFilePath] = NO) {[fileManager createFileAtPath: [self getFilePath] contents: nil attributes: nil];} // Write File _ fileHandle = [NSFileHandle fileHandleForWritingAtPath: [self getFilePath];}-(void) connection :( NSURLConnection *) connection didReceiveData :( NSData *) data {// if the file is large, multiple writes are required, you need to move the cursor to the end of [_ fileHandle seekToEndOfFile]; // write data to the file [_ fileHandle writeData: data]; // The size of the latest received data is equal to the size of the existing data in the file, plus the size of the downloaded data _ receiveSize = _ receiveSize + data. length; // calculate the progress float jundu = (float) _ receiveSize/_ totalSize; // use the progress bar to indicate the progress _ progress. progress = jundu;}-(void) connectionDidFinishLoading :( NSURLConnection *) connection {// file transfer completed, close file management [_ fileHandle closeFile];}-(IBAction) pause :( id) sender {// click pause to cancel connection request [_ connection cancel]; _ connection = nil;}-(NSString *) getFilePath {NSString * documentsPath = NSSearchPathForDirectoriesInDomains (NSDocumentDirectory, NSUserDomainMask, YES) [0]; NSString * filePath = [documentsPath stringByAppendingPathComponent: @ "xcode. dmg "]; return filePath ;}

 

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.