In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-03-31 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article is about how iOS can download files. The editor thinks it is very practical, so share it with you as a reference and follow the editor to have a look.
The basic principle of segmented download of original ecology
File downloading often takes a long time, and the realization of segmented download is the premise of breakpoint download.
The following two problems need to be solved to realize segmented download
Question 1: before downloading, you need to know the length of the file.
Question 2: a section of each request to download a file
Get the file length for the problem 1:HEAD request
The HEAD request only gets the response message, not the actual data of the resource.
It is usually used to obtain the file length and to detect whether the server-side resources have changed.
The property exceptedContentLength of the response object NSURLResponse indicates the length of the file
For problem 2: request header parameter Range for segmented download
The HTTP protocol stipulates that the Range parameter in the request header is used to request a piece of data.
Such as:
The first 500bytes of bytes=0-499 from 0 to 499
Second 500byte of bytes=500-999 from 500to 999
Bytes=500- all bytes after 500byte
The last 500bytes of bytes=-500
Bytes=500-599800-899 specifies several ranges simultaneously
That is to say, download in segments means sending multiple requests and setting the Range field for each request.
The following code completes the segmented download of a file:
The following code completes a download of the file:
When using asynchronous downloads, agents, notifications, and block should be used for post-download processing actions.
Download task for NSURLSession
Download task creation:
-(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
Proxy methods related to NSURLSession performing download tasks:
/ / periodic call. Parameters describe the download progress-(void) URLSession: (NSURLSession *) session downloadTask: (NSURLSessionDownloadTask*) downloadTask didWriteData: (int64_t) bytesWritten totalBytesWritten: (int64_t) totalBytesWritten totalBytesExpectedToWrite: (int64_t) totalBytesExpectedToWrite//. Call-(void) URLSession: (NSURLSession *) session downloadTask: (NSURLSessionDownloadTask*) downloadTask didFinishDownloadingToURL: (NSURL *) location when the download is complete.
The example shows:
1) create a NSURLSession object and specify a proxy
2) create a download task and start it
3) Agent method for download completion: the downloaded files should be moved to the specified directory and renamed
4) proxy method to monitor download progress:
Download the implementation of pause / resume
Pause method for NSURLSessionDownloadTask:
-(void) cancelByProducingResumeData: (void (^) (NSData * resumeData)) completionHandler
Parameter resumeData: describes breakpoint information
NSURLSession creates 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
An example shows:
1) download pause
2) download continues
3) proxy method for breakpoint to continue downloading
Download using AFNetworking
Downloading using AFNetworking essentially creates a NSURLSessionDownloadTask object
Simply encapsulate the proxy method in an AFURLSession object and specify the behavior with block
AFURLSessionManager create download task
/ / create a download task based on the 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// creates a love download task based on breakpoint information-(NSURLSessionDownloadTask *) downloadTaskWithResumeData: (NSData *) resumeData progress: (NSProgress * _ nullable _ autoreleasing * _ nullable) progress destination: (nullable NSURL * (^) (NSURL * targetPath, NSURLResponse * response) destination completionHandler: (nullable void (^) (NSURLResponse * response, NSURL * filePath, NSError * error)) completionHandler
Parameter destination: this block is used to specify the path after the file is downloaded.
Parameter completionHandler: this block is executed when the download task is completed
Including when the task is paused (cancelByProducingResumeData)
Output parameter progress: if it is not NULL, a NSProgress object is returned to describe the download progress
The example shows:
1) create a NSURLSession object and specify a proxy
2) block wrapper 1: the final storage URL of the downloaded file should be returned.
3) Task completion block encapsulation: including processing in case of error, prompt in case of successful request, etc.
4) start / continue the creation of the download task
5) suspension of download task
Use NSProgress to monitor download progress
In the above code, there is a parameter of type NSProgress, which is passed as NULL, which is used by the AFN framework to listen for download progress.
NSProgress is introduced in iOS7.0, using observer mode
Notify all observers when the value of its fractionCompleted attribute changes
The example shows:
1) start / continue the creation of the download task
2) the response method of KVO
Where self.progressView is a custom view object that displays the progress of the download
Download tasks often encounter situations
Condition 1: how to save the download status when the program exits
Download the task management class and register as a responder to the following UIApplication object notifications
UIApplicationDidEnterBackgroundNotification
UIApplicationWillTerminateNotification
Response method implementation: pause all download tasks and save breakpoint information to the local operation
Read breakpoint information locally in response to the following notification
UIApplicationWillEnterForegroundNotification
Or the operation of reading breakpoint information locally when the download task management object is created
Condition 2: what should I do if the file on the server changes or is deleted when I continue to download from the breakpoint?
You can send a HEAD request to determine whether the file exists and whether the length of the file has changed before continuing the download from the breakpoint.
Thank you for reading! This is the end of this article on "how to download iOS files". I hope the above content can be helpful to you, so that you can learn more knowledge. if you think the article is good, you can share it out for more people to see!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.