iOS Development-File Download (6 compression and decompression)

Source: Internet
Author: User

iOS Development Network Chapter-File download (six • Compression and decompression)

First, complete the file download

Requirements: Complete File download

1. In the local server, add a compressed file for the picture.

2. code example:

File Downloader code:

Header file

1//2//  YYfileDownloader.h 3//  01-File Download (unreasonable) 4//5//Created by  Apple on 14-7-1.6//  Copyright (c) 2 014 Years itcase. All 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:

  1//2//YYFILEDOWNLOADER.M 3//01-File Download (unreasonable) 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 37//Send request (using proxy method) 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:@ "Images.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}108109/*110 * When the server's data is loaded, it calls 111 */112-(void) connectiondidfinishloading: (nsurlconnection *) connection113 {NSLog (@ "Download completed----%lld", self.sumlength); 115//close connection, no longer input data in the 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 (failure) when called (Request timeout \ 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 next Face code 141//^{142//NSLog (@ "Download error!) "); 143//}144}145}146 147 @end

Control code in the host controller:

 1//2//YYVIEWCONTROLLER.M 3//01-File Download (unzip) 4//5//Created by Apple on 14-7-2. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" #import "YYfileDownloader.h" @interface Yyviewcontroller () @property (Nona Tomic,strong) Yyfiledownloader *filedownloader;14//@property (weak, nonatomic) Iboutlet UIButton *btn;15 @property ( Weak, nonatomic) Iboutlet uiprogressview *progress;16 @end17 @implementation YYViewController19-(void) viewdidload [Super viewdidload];23}24 #pragma mark-lazy load-(Yyfiledownloader *) fileDownloader27 {if (_filedownloa Der==nil) {_filedownloader=[[yyfiledownloader alloc]init];30//Setup file download path [email protected ] "Http://192.168.1.53:8080/MJServer/resources/images.zip"; 32 33//Set File save path NSString *caches=[nss Earchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastobject];35 NSString *filePath=[cach Es stringbyappendingpathcomponent:@ "Images.zip"];36 _filedownloader.destpath=filepath;37 _fileDownloader. progresshandler=^ (double progress) at NSLog (@ "Download progress-----%f", progress);};42 _filed         ownloader.completionhandler=^{43 NSLog (@ "Download Complete"), 44//After the download is complete, unzip the file 45 46};47 _filedownloader.failurehandler=^ (Nserror *error) {NSLog (@) Download Error! %@ ", error);};50}51 return _filedownloader;52}53 54//When the finger touches the screen, download the compressed file (void) Touchesbegan: (Nsset * ) Touches withevent: (uievent *) event56 {self.filedownloader start];58}59 @end

3. Print View:

In the sandbox, view the data that you downloaded.

Second, to achieve decompression

Requirements: After the download is complete, unzip the file

Description: Use a pure C-language library for decompression.

1. Description of the third-party decompression framework:

Third party decompression Frame--ssziparchive

: https://github.com/samsoffes/ssziparchive

Note: The Libz.dylib framework needs to be introduced

(1) Decompression

NSString *zippath = @ "Path_to_your_zip_file";

NSString *destinationpath = @ "path_to_the_folder_where_you_want_it_unzipped";

[Ssziparchive Unzipfileatpath:zippath Todestination:destinationpath];

(2) compression

NSString *zippedpath = @ "path_where_you_want_the_file_created";

Nsarray *inputpaths = [Nsarray arraywithobjects:

[[NSBundle Mainbundle] pathforresource:@ "photo1" oftype:@ "jpg"],

[[NSBundle Mainbundle] pathforresource:@ "Photo2" oftype:@ "jpg"]nil];

[Ssziparchive Createzipfileatpath:zippedpath withfilesatpaths:inputpaths];

(3) Illustration

2. Use:

(1) Importing third-party frameworks

  

(2) Import header file

(3) Click to run directly will error. The reason is that it lacks a library, and the use of this framework relies on the Libz.dylib library, which needs to be imported into the library for use.

(4) Running the program, code example

The decompression function implementation code is as follows:

 1//2//YYVIEWCONTROLLER.M 3//01-File Download (unzip) 4//5//Created by Apple on 14-7-2. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" #import "YYfileDownloader.h" #import "SSZipArchive.h" @interface Yyviewcon Troller () @property (nonatomic,strong) Yyfiledownloader *filedownloader;15//@property (weak, nonatomic) Iboutlet UIButton *btn;16 @property (weak, nonatomic) Iboutlet uiprogressview *progress;17 @end18 @implementation Yyviewcontrol Ler20-(void) viewDidLoad22 {[Super viewdidload];24}25 #pragma mark-lazy load-(Yyfiledownloader *) Filedownloade         R28 {if (_filedownloader==nil) {_filedownloader=[[yyfiledownloader alloc]init];31//Set File download path 32         [email protected] "Http://192.168.1.53:8080/MJServer/resources/images.zip"; 33 34//Set File save path 35         NSString *caches=[nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES) lastObject];36 NsstrinG *filepath=[caches stringbyappendingpathcomponent:@ "Images.zip"];37 _filedownloader.destpath=filepath;38         _filedownloader.progresshandler=^ (double progress) NSLog (@ "Download progress-----%f", progress), 42            };43 _filedownloader.completionhandler=^{44 NSLog (@ "Download complete"); 45//download, unzip the file 46 Unzip downloaded compressed files using a third-party framework 47//NOTE: If the file is large, the decompression process will be time consuming, so it is best to put it on an asynchronous thread to perform the Dispatch_async (dispatch_ge             T_global_queue (Dispatch_queue_priority_default, 0), ^{49//Parameter description: The first parameter is the file path to extract, the second parameter is the extracted file save path 50             [Ssziparchive Unzipfileatpath:filepath todestination:caches];51 NSLog (@ "-----%@", [Nsthread CurrentThread]); 52 NSLog (@ "has been unzipped done! "),};56 _filedownloader.failurehandler=^ (Nserror *error) {NSLog (@ "Download Error! %@ ", error);};59}60 return _filedownloader;61}62 63//When the finger touches the screen, download compressed file (void) Touchesbegan:(Nsset *) touches withevent: (uievent *) event65 {[Self.filedownloader start];67}68] @end 

To view the sandbox:

Print View:

Third, compressed files

Requirement: Compress the picture and write to the sandbox cache

1. Add a picture to your project for demonstration

2. Sample Code

 1//2//YYVIEWCONTROLLER.M 3//01-File Download (unzip) 4//5//Created by Apple on 14-7-2. 6//Copyright (c) 2014 itcase. All rights reserved. 7//8 9 #import "YYViewController.h" #import "YYfileDownloader.h" #import "SSZipArchive.h" @interface Yyviewcon Troller () @property (nonatomic,strong) Yyfiledownloader *filedownloader;15//@property (weak, nonatomic) Iboutlet UIButton *btn;16 @property (weak, nonatomic) Iboutlet uiprogressview *progress;17 @end18 @implementation Yyviewcontrol Ler20 21//When the finger touches the screen, compress the file (void) Touchesbegan: (Nsset *) touches withevent: (uievent *) event23 {+//[Self.filedown Loader start];25//[[NSBundle mainbundle]pathforresource:@ "minion_01.png" oftype:nil];26//[[NSBundle MainBundle] pathforresource:@ "Minion_01.png" oftype:nil];27 28//1. Get all PNG images in Mainbundle nsarray *pngs=[[nsbundle MainB undle]pathsforresourcesoftype:@ "PNG" indirectory:nil];30 nsstring *caches=[nssearchpathfordirectoriesindomains ( NscachesdirEctory, Nsuserdomainmask, YES) lastobject];32 nsstring *filepath=[caches stringbyappendingpathcomponent:@ "Img.zip"]; 33//The first parameter is the compressed file path, the second parameter is the compressed file array of the [ssziparchive Createzipfileatpath:filepath withfilesatpaths:pngs];35 36}3 7 @end

To view the sandbox:

Note: The path must be a full path.

Tags: iOS development, network chapter

iOS Development-File Download (6 compression and decompression)

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.