如何下载&在iOS上解压缩文件 [英] How to download & unzip files on iOS

查看:155
本文介绍了如何下载&在iOS上解压缩文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想下载包含我的应用程序的mp3的zip文件。然后,我需要将其解压缩到一个永久的目录中,其中包含要按需播放的mp3。这是一个词汇应用程序,zip文件包含要提取的mp3。大约5 MB的zip文件。

I'd like to download a zip file containing mp3s for my app. Then, I will need to unzip it into a permanent directory, which will contain the mp3s to be played on demand. This is a vocabulary app and the zip file contains the mp3s to be extracted. The zip file as about 5 MB.

更多问题:什么是好的目录下载到?如何解压缩?此外,文件,或者更确切地说,它们所在的Web目录是受密码保护的,因此我需要提供名称和密码。有没有人有任何一般的指针吗?

More questions: What's a good directory to download these to? How to do unzipping? Also, the files, or rather, the web directory they are in, is password protected, so I will need to provide the name and password.

特别是,我想知道如何提供用户名/密码,下载的最佳目录,如何解压文件以及如何下载。任何代码示例将不胜感激。

Does anyone have any general pointers? In particular, I'd like to know how to provide the user name / password, the best directory to download to, how to unzip the file, and how to download. Any code samples would be greatly appreciated.

推荐答案

首先,要下载受密码保护的文件,您需要一个NSURLConnection,该类需要实现 NSURLConnectionDelegate 协议,以处理身份验证请求。 这里的文档

First step, to download password protected files you need an NSURLConnection, the class it's in needs to implement the NSURLConnectionDelegate protocol in order to handle authentication requests. Docs here.

为了永久保存这些文件,您必须将其保存到应用程序文档目录中。 (请记住,默认情况下,这里的所有文件都备份到iCloud,这里有很多MP3会驱动iCloud备份大小太远,Apple可能会拒绝您的应用程序,简单的解决方案是关闭iCloud备份您下载的每个文件/解压缩到您的文档目录)

In order to store these permanently, you have to save them to the app Documents directory. (Bear in mind that by default all files in here are backed up to iCloud, having lots of MP3s in here will drive the iCloud backup size too far and Apple may reject your app for that. Simple fix for this is to just turn off iCloud backup for each file you download/unzip to your documents directory).

接下来,如果您有正确的工具,解压缩是相当简单的,我已经取得了很大成功使用 Objective-Zip库。维基中的一些方便的代码示例就是使用这个。

Next, unzipping is fairly straightforward if you have the right tools, I've had great success implementing this using the Objective-Zip library. Some handy code samples in the Wiki on the usage of this.

所以在你的情况下,这个过程将是这样的:

So in your case, the process will be along the lines of:


  1. 在服务器上创建一个 NSURLConnection ,在使用身份验证挑战委托方法提示时提供用户名和密码。 li>
  2. 使用类似于以下代码块的NSURLConnection下载代理。 将收到的字节附加到磁盘上的文件(而不是继续附加到NSMutableData对象)是更安全的做法,如果您的zip文件太大,不能完全保留在内存中,您将经常遇到崩溃

  1. Create an NSURLConnection to the server, providing the username and password when prompted using the authentication challenge delegate methods.
  2. Use the NSURLConnection download delegates similar to the below code block. It's safer practice to append the received bytes to the file on disk as you receive it (rather than keep appending it to an NSMutableData object), if your zip files are too large to keep entirely in memory you'll experience frequent crashes.

// Once we have the authenticated connection, handle the received file download:
-(void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
    NSFileManager *fileManager = [NSFileManager defaultManager];

    // Attempt to open the file and write the downloaded data to it
    if (![fileManager fileExistsAtPath:currentDownload]) {
        [fileManager createFileAtPath:currentDownload contents:nil attributes:nil];
    }
    // Append data to end of file
    NSFileHandle *fileHandle = [NSFileHandle fileHandleForWritingAtPath:currentDownload];
    [fileHandle seekToEndOfFile];
    [fileHandle writeData:data];
    [fileHandle closeFile];
}


  • 现在你已经完全下载了ZipFile, Zip,应该看起来像这样(再次,这种方法是伟大的,因为它缓冲文件,所以即使大型文件解压也不应该引起内存问题!)

    -(void)connectionDidFinishLoading:(NSURLConnection *)connection {
    
        // I set buffer size to 2048 bytes, YMMV so feel free to adjust this
        #define BUFFER_SIZE 2048
    
        ZipFile *unzipFile = [[ZipFile alloc] initWithFileName:zipFilePath mode:ZipFileModeUnzip];
        NSMutableData *unzipBuffer = [NSMutableData dataWithLength:BUFFER_SIZE];
        NSArray *fileArray = [unzipFile listFileInZipInfos];
        NSFileHandle *fileHandle;
        NSFileManager *fileManager = [NSFileManager defaultManager];
        NSString *targetFolder = folderToUnzipToGoesHere;
        [unzipFile goToFirstFileInZip];
        // For each file in the zipped file...
        for (NSString *file in fileArray) {
            // Get the file info/name, prepare the target name/path
            ZipReadStream *readStream = [unzipFile readCurrentFileInZip];
            FileInZipInfo *fileInfo = [unzipFile getCurrentFileInZipInfo];
            NSString *fileName = [fileInfo name];
            NSString *unzipFilePath = [targetFolder stringByAppendingPathComponent:fileName];
    
            // Create a file handle for writing the unzipped file contents
            if (![fileManager fileExistsAtPath:unzipFilePath]) {
                [fileManager createFileAtPath:unzipFilePath contents:nil attributes:nil];
            }
            fileHandle = [NSFileHandle fileHandleForWritingAtPath:unzipFilePath];
            // Read-then-write buffered loop to conserve memory
            do {
                // Reset buffer length
                [unzipBuffer setLength:BUFFER_SIZE];
                // Expand next chunk of bytes
                int bytesRead = [readStream readDataWithBuffer:unzipBuffer];
                if (bytesRead > 0) {
                    // Write what we have read
                    [unzipBuffer setLength:bytesRead];
                    [fileHandle writeData:unzipBuffer];
                } else
                   break;
            } while (YES);
    
            [readStream finishedReading];
            [fileHandle closeFile];
            // NOTE: Disable iCloud backup for unzipped file if applicable here!
            /*...*/
    
            [unzipFile goToNextFileInZip];
        }
    
        [unzipFile close]; // Be sure to also manage your memory manually if not using ARC!
    
        // Also delete the zip file here to conserve disk space if applicable!
    
    }
    


  • 您现在应该已经解压缩了下载的zip文件到文件目录的所需子文件夹,文件可以使用!

  • You should now have unzipped the downloaded zip file to your desired sub-folder of the Documents directory, and the files are ready to be used!

    这篇关于如何下载&在iOS上解压缩文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

  • 查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆