Using ziparchive compression and decompression files in iOS

Source: Internet
Author: User
Tags ziparchive

Why do I need to unzip a file

There are a number of reasons why I want to use compression and decompression in my project, and here are a few common reasons:


50M download limit for Apple App Store

For traffic reasons, Apple restricts users to downloading apps or games that are less than 50M in a non-WiFi environment. In this way, for some applications with large data or packets, we can only minimize the size of the application binary package. And the data is packaged in a zip, so that the app can download packets over the network, extract the required content, and this can also dynamically update the content.


Dynamically update content

This has been mentioned above. If the resources needed for the app need to be updated dynamically, a common practice is to update the resources, repackage them, resubmit them to the App Store, and you'll need to wait for a lengthy review and shelf time. In general it is a week or so of time. A better approach is to package these resources on the server, download the app from the server (or cloud storage), and unzip it. The advantages of this are obvious, that is, can be quickly updated, dynamic update, do not need to repackage, upload, audit, save time and effort.


Downloading a zip file from the Web

Safari and mail programs do not support zip viewing, and by ziparchive you can add the ability to view ZIP files for your device, although there are already apps in the App store that support these features.


Project Setup

First check out a code on Google Code, the SVN address is: http://ziparchive.googlecode.com/svn/trunk/ziparchive-read-only

You can check out by entering the following command in the terminal:

SVN Co http://ziparchive.googlecode.com/svn/trunk/ziparchive-read-only

or download it directly from Http://ziparchive.googlecode.com/files/ZipArchive.zip.

Add the Minizip folder and the ZipArchive.h and ziparchive.mm files to your project.

Because Ziparchive does not support arc, if your project opens arc, then you need to set the ziparchive. In the ziparchive.mm compilation option, add -fno-objc-arc .

Finally, the LIBZ dynamic link library needs to be linked to the project.

At this point, ziparchive has been integrated into your project, compile the project, should be able to compile successfully. There may be some caveats, which are irrelevant and do not affect compilation. But as a rigorous programmer, I strongly recommend that you take a look at how these warnings appear and resolve them. Remember: In your project, warnings should be treated as seriously as errors!


Download and Decompress files

The next step is to show you how to download the zip file from the Web in your project, unzip it, and read the contents of the file in the zip archive. In the demonstration, the main purpose is to show you how to use the Ziparchive interface, so the error handling and condition checking of the code is not too much to consider, in the actual project, we still need to do more stringent condition check and error handling work.

Example projects run with the following effects:




The project only adds a uiimageview and a uilabel to the Viewcontroller. We will download the zip file from the network, and the zip file contains a picture and a text file. When the download is unpacked, the image is rendered to Uiimageview, and the text is displayed as Uilabel content. The sample code is at the end of the article. I hope readers will download, compile, and view the results themselves.

OK, let's talk about specific implementations:


1. Introduce the ziparchive header file.

    1. #import "ZipArchive.h"
Copy Code

2. Download the zip file

  1. 1
  2. dispatch_queue_t queue = Dispatch_get_global_queue (
  3. Dispatch_queue_priority_default, 0);
  4. Dispatch_async (Queue, ^{
  5. Nsurl *url = [Nsurl urlwithstring:@ "Http://www.icodeblog.com/wp-content/uploads/2012/08/zipfile.zip"];
  6. Nserror *error = nil;
  7. 2
  8. NSData *data = [NSData datawithcontentsofurl:url options:0 error:&error];
  9. if (!error)
  10. {
  11. 3
  12. Nsarray *paths = Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES);
  13. NSString *path = [Paths objectatindex:0];
  14. NSString *zippath = [path stringbyappendingpathcomponent:@ "Zipfile.zip"];
  15. [Data Writetofile:zippath options:0 error:&error];
  16. if (!error)
  17. {
  18. Todo:unzip
  19. }
  20. Else
  21. {
  22. NSLog (@ "Error saving file%@", error);
  23. }
  24. }
  25. Else
  26. {
  27. NSLog (@ "Error downloading zip file:%@", error);
  28. }
  29. });
Copy Code

The main function of the above code is to download a zip file from Icodeblog and write it to the application's cache directory.

Now that the zip file has been downloaded, the next step is to extract the extracted files and use them.


3. Unzip the downloaded zip file

In the second step, we have downloaded the zip file to /library/caches/zipfile.zipand now unzip it.

Replace the //todo:unzip in the above code with the following code.

  1. Ziparchive *za = [[Ziparchive alloc] init];
  2. 1
  3. if ([za unzipopenfile:zippath]) {
  4. 2
  5. BOOL ret = [za unzipfileto:path overwrite:yes];
  6. if (NO = = ret) {} [za unzipclosefile];
  7. 3
  8. NSString *imagefilepath = [path stringbyappendingpathcomponent:@ "Photo.png"];
  9. NSString *textfilepath = [path stringbyappendingpathcomponent:@ "Text.txt"];
  10. NSData *imagedata = [NSData datawithcontentsoffile:imagefilepath options:0 Error:nil];
  11. UIImage *img = [UIImage imagewithdata:imagedata];
  12. NSString *textstring = [NSString Stringwithcontentsoffile:textfilepath
  13. Encoding:nsasciistringencoding Error:nil];
  14. 4
  15. Dispatch_async (Dispatch_get_main_queue (), ^{
  16. Self.imageView.image = img;
  17. Self.label.text = TextString;
  18. });
Copy Code

Make a simple explanation of the above code:

1. Unzip the file in memory

2. Write the extracted content to the cache directory

3. Using the extracted files

4. Updating the UI

It's very simple!


Compress files

Next look at how to compress the files. In the above steps, we have extracted a zip file into the cache directory. Now we re-compress the extracted files into a zip file and write the zip file to the documents directory (OMG, these two files are too miserable, repeatedly torn)

In the sample project code, I have added a button and associated with a ibaction, the button's handler function is named zipfilesbuttonpressed:, the code is as follows:

  1. -(Ibaction) zipfilesbuttonpressed: (ID) sender
  2. {
  3. 1
  4. Nsarray *paths = Nssearchpathfordirectoriesindomains (NSDocumentDirectory, Nsuserdomainmask, YES);
  5. NSString *docspath = [Paths objectatindex:0];
  6. 2
  7. paths = Nssearchpathfordirectoriesindomains (Nscachesdirectory, Nsuserdomainmask, YES);
  8. NSString *cachepath = [Paths objectatindex:0];
  9. 3
  10. NSString *zipfile = [Docspath stringbyappendingpathcomponent:@ "Newzipfile.zip"];
  11. 4
  12. Ziparchive *za = [[Ziparchive alloc] init];
  13. [Za createzipfile2:zipfile];
  14. 5
  15. NSString *imagepath = [CachePath stringbyappendingpathcomponent:@ "Photo.png"];
  16. NSString *textpath = [CachePath stringbyappendingpathcomponent:@ "Text.txt"];
  17. 6
  18. [Za addfiletozip:imagepath newname:@ "newphotoname.png"];
  19. [Za addfiletozip:textpath newname:@ "NewTextName.txt"];
  20. 7
  21. BOOL success = [Za CloseZipFile2];
  22. NSLog (@ "Zipped file with result%d", success);
  23. }
Copy Code

Simply explain the meaning of the above code:

1. Get the documents directory, and the new zip file will be written to this directory.

2. Get the caches directory, the file to be compressed in this directory.

3. Get the full path name of the zip file.

4. Create an ziparchive instance and create an in-memory zip file. It is important to note that the zip file is only written to disk from memory after you call the CloseZipFile2 method.

5. Get the full path of the file to be compressed

6. Add the files you want to compress into the Zip object, the number of files added is unlimited, or you can add folders to the Zip object.

7. Write the zip from memory to disk.

When the button is clicked, there should be a file called Newzipfile.zip under the Documents folder of the app. Unzip the file and extract the two files that have been repeatedly torn.


Conclusion

Now you know how to compress and decompress files using Ziparchive. Enjoy the convenience of ziparchive. The example project has already shown these basic usages well, and you can study it carefully.


Example Project :ziptest.zip (179.4 KB)

Using ziparchive compression and decompression files in iOS

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.