iOS Development Network Chapter-File Download (five • Package for download function)
A simple explanation
In the previous articles on the basis of the download code, this article analyzes the download function encapsulation.
Through the previous code, we found that just downloading a file requires writing a very long code, so if you want to download multiple files, you need to write multiple copies of the code. Here, we encapsulate the code that downloads a file. The controller needs only to know which file to download and which path to download.
After the download function is encapsulated, add a file downloader, a file downloader download only one file, after encapsulation if you want to download multiple files, then only need to create multiple file Downloader object can be controlled and downloaded.
Second, code example
1. Code:
Create a new class to inherit from the NSObject class, and a file downloader downloads only one file.
The header file code for the custom class:
1//2// YYfileDownloader.h 3// 4//5// Created by Apple on 14-7-1.6// Copyright (c) 2014 itcase. A ll rights reserved. 7//8 9 #import <foundation/foundation.h>10 @interface yyfiledownloader:nsobject12//Download remote URL (path connected to server) @property (Nonatomic,strong) nsstring *url;14//Downloaded storage path (where files are downloaded) @property (nonatomic,strong) NSString * DESTPATH;16//is downloading (only clear inside the downloader) @property (nonatomic,readonly,getter = isdownloading) BOOL downloading;18// Used to listen for download Progress @property (nonatomic,copy) void (^progresshandler) (double progress), 20//To listen for download completed @property (nonatomic, copy) void (^completionhandler) (), 22//To listen for download errors @property (nonatomic,copy) void (^failurehandler) (Nserror *error); 24 -(void) pause;25-(void) start;26 @end
Implementation code for the custom class:
1//2//YYFILEDOWNLOADER.M 3//4//5//Created by Apple on 14-7-1. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYfileDownloader.h" @interface Yyfiledownloader () <NSURLConnectionDataDelegate> 12//Request to Like @property (Nonatomic,strong) nsurlconnection *cnnt; 14//File handle @property (Nonatomic,strong) Nsfilehandle *writehandle; 16//Currently acquired data length @property (nonatomic,assign) long long currentlength; 18//Full data length @property (nonatomic,assign) long long sumlength; @end @implementation Yyfiledownloader 23//Start download-(void) Start _downloading=yes; 27 28 Create a request Nsurl *url=[nsurl URLWithString:self.url]; Nsmutableurlrequest *request=[nsmutableurlrequest Requestwithurl:url]; 31 32//Set request header information//self.currentlength byte part restart read nsstring *value=[nsstring stringwithformat:@ "bytes=% Lld-", Self.currentlength]; [Request Setvalue:value forhttpheaderfield:@ "Range"]; 36 37Send request (How to use proxy) self.cnnt=[nsurlconnection connectionwithrequest:request delegate:self]; 39 40} 41 42//Pause download-(void) pause $ {_downloading=no; 46//Cancel send request [self.cnnt Cancel]; . Cnnt=nil; #pragma mark-nsurlconnectiondatadelegate Agent Method 52/* 53 * When receiving a response from the server (connected to the server) will call the "* * * * * * * * Connection: (N Surlconnection *) connection didreceiveresponse: (nsurlresponse *) Response #warning Determine if it is the first time to connect the IF (self.sumle Ngth) return; 59 60//1. Creating a File Save path NSString *caches=[nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainma SK, YES) Lastobject]; NSString *filepath=[caches stringbyappendingpathcomponent:@ "Video.zip"]; 63 64 65 66//2. Create an empty file, into the sandbox nsfilemanager *mgr=[nsfilemanager Defaultmanager]; 68//Newly created size is O byte [Mgr Createfileatpath:filepath contents:nil Attributes:nil]; 70 71//3. Create a file handle to write data Self.writehandle=[nsfilehandle FILEHANDLEFORWRITINGATPATh:filepath]; 73 74//4. Get the full file length of self.sumlength=response.expectedcontentlength; 76} 77 78/* 79 * Called when data is received from the server (may be called multiple times, only part of the data is delivered at a time) */Bayi-(void) connection: (Nsurlconnection *) connection Didreceiv EData: (NSData *) data 82 {83//cumulative received to the length of self.currentlength+=data.length; 85//Calculate the progress value of * * Double progres S= (double) self.currentlength/self.sumlength; Self.progress.progress=progress//; if (Self.progresshandler) {//Pass the progress value to block Self.progresshandler (progress); 90 91//equivalent here Called the following code of the progress//^ (double) 93//{94/////The value of the progress is passed to the controller progress bar to display the Vc.prog ress.progress=progress; 96//}; 97} 98 99 100//1.1 receive data. 101 NSLog (@ "Receive data from the server! ---%d ", data.length); 102//writes data to the created empty file, but cannot use WriteToFile (overwrites) 103//To move to the end of the file 104 [Self.writehandle Seektoendo ffile];105//From the current moving position, write data 106 [self.writehandle writedata:data];107}108 109/*110 * When the serverWhen the data is loaded, 111 */112-(void) connectiondidfinishloading: (nsurlconnection *) connection113 {NSLog (@ "Downloaded----%lld" , self.sumlength); 115//close connection, no longer input data in file [Self.writehandle closefile];117 self.writehandle=nil;118 119 Empty progress value self.currentlength=0;121 self.sumlength=0;122 123 if (Self.completionhandler) {//Download complete notification Controller 124 Self.completionhandler (); 125//equivalent to the following code 126//^{127//NSLog (@ "Download complete"); 128// [self.btn settitle:@ "Download Completed" forstate:uicontrolstatenormal];129//}130}131 132}133/*134 * Request error (failed) call (request Timeout \ Broken network \ No net \, generally referred to as client error 135 */136-(void) connection: (Nsurlconnection *) connection didfailwitherror: (Nserror *) error137 { 138 if (Self.failurehandler) {//Notification controller, download error 139 Self.failurehandler (error), 140//equivalent to call the following code 141//^{ 142//NSLog (@ "Download error!) "); 143//}144}145}146 147 @end
Main controller code:
1//2//YYVIEWCONTROLLER.M 3//01-File Download (unreasonable) 4//5//Created by Apple on 14-6-30. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" #import "YYfileDownloader.h" @interface Yyviewcontroller () @property (n Onatomic,strong) Yyfiledownloader *filedownloader;15 @property (weak, nonatomic) Iboutlet UIButton *btn;16 @property ( Weak, nonatomic) Iboutlet uiprogressview *progress;17 @end18 @implementation YYViewController20-(void) viewdidload [Super viewdidload];24}25 #pragma mark-lazy load-(Yyfiledownloader *) fileDownloader28 {if (_filedownloa Der==nil) {_filedownloader=[[yyfiledownloader alloc]init];31//Setup file download path [email protected ] "Http://192.168.1.53:8080/MJServer/resources/video.zip"; 33 34//Set File save path NSString *caches=[nsse Archpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject];36 NSString *filePath=[cache S Stringbyappendingpathcomponent:@ "Video.zip"];37 _filedownloader.destpath=filepath;38 39//Get 10 of the true type and put it As the type of A, typeof (Ten) A = 20; int a = 20;41 __weak typeof (self) vc=self;42 _filedownloader.progresshandler=^ (double progress) 43 {vc.progress.progress=progress;45 NSLog (@ "%f", progress);};47 _filedownloa der.completionhandler=^{48 NSLog (@ "Download complete"), [vc.btn settitle:@ "Download Completed" Forstate:uicontrolstatenor Mal];50};51 _filedownloader.failurehandler=^ (nserror *error) {NSLog (@ "Download error!) %@ ", error);};54}55 return _filedownloader;56}57 58//Click the Download button to process operation-(ibaction) star {if (self). filedownloader.isdownloading) {//If you are downloading, the call method pauses the Self.filedownloader pause];62 [self.btn settitle:@ "Pause" forstate:uicontrolstatenormal];63}else//If you are not downloading, then call the Download method (Self.filedownloader start];66 [ Self.btn settitle:@ "Download" forstate:uicontrolstatenormal];67}68}69 @end
2. Code description
To get the download progress in the controller, you can use a proxy or block, which is implemented using block.
To pass a block of download progress to the downloader, every time, the downloader calls the block, and then passes the progress information to the external progress bar for display.
/* * Called when data is received from the server (may be called multiple times, only partial data is delivered at a time) */-(void) connection: (Nsurlconnection *) connection didreceivedata: (NSData *) data{ //accumulate the received data length self.currentlength+=data.length; Calculate the progress value double progress= (double) self.currentlength/self.sumlength;// self.progress.progress=progress; if (Self.progresshandler) {//Pass the progress value to block Self.progresshandler (progress); Equivalent to calling the following code here// ^ (double progress)//{/////To pass the progress value to the controller progress bar for display// vc.progress.progress =progress;// }; }
To listen for progress values in the controller:
_filedownloader.progresshandler=^ (double progress) { vc.progress.progress=progress; NSLog (@ "%f", Progress); };
The controller wants to listen to the download progress of the Downloader, the controller wants to listen to the download of the downloader, the controller would like to listen to the download failure of the downloader, etc. can be used block way.
Print View:
Third, supplementary
In iOS development, sometimes we need to make improvements based on old projects that already exist, and here's how to change the name of the project and the file.
(1) After opening the project, click Modify Project name.
(2) After the modification, click Enter, pop up the following window.
(3) on the navigation bar, click.
(4) Change the name, then click OK.
(5) Modify the name of the remaining two files.
At this point, all the changes have been completed.
Tags: iOS development, network chapter
iOS Development-File Download (5 download feature package)