0

我在 URL 上有一个 .zip 文件,我想下载它,解压缩并将其保存到 nsdocument 目录中,无需任何 UI 或用户交互。然后回读。

4

2 回答 2

1

在 .h 文件中声明此变量

NSMutableData *responseData;

在您的 viewDidLoad 方法中编写此代码此方法将开始从给定 URL 下载文件

NSURL *serverURL = [NSURL URLWithString:@"your file URL here"];
NSURLRequest *request = [NSURLRequest requestWithURL:serverURL];
NSURLConnection *cn = [NSURLConnection connectionWithRequest:request delegate:self];
[cn start];

在 .m 文件中实现这个 Delegate 方法

#pragma mark - NSURLConnection Delegate Methods
- (void)connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
    NSLog(@"%s",__FUNCTION__);
    responseData = nil;
}

- (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
    NSLog(@"%s",__FUNCTION__);
    responseData = [[NSMutableData alloc] initWithCapacity:0];
}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)data
{
    NSLog(@"%s",__FUNCTION__);
    [responseData appendData:data];
}


- (void)connectionDidFinishLoading:(NSURLConnection *)connection
{
    NSLog(@"%s",__FUNCTION__);

    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *docDirPath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
    NSString *filePath = [docDirPath stringByAppendingPathComponent:@"DownloadedZip.zip"];

    // Save file to Document Directory
    [responseData writeToFile:filePath atomically:YES];
    responseData = nil;
}

在此处下载项目到 unArchive zip 文件,并在将文件保存到 Document Directory 后放入 unArchive Code

于 2013-04-11T18:11:33.800 回答
0

首先将文件下载到您的设备。

NSString *URLstring = @"http://your.download.URL";
NSURL  *url = [NSURL URLWithString:URLstring];
NSData *urlData = [NSData dataWithContentsOfURL:url];

然后将其写入设备。ThePath 是您要在设备上保存的位置以及要保存的文件名,请记住添加文件扩展名 (.zip)。

[urlData writeToFile:thePath atomically:YES];

然后你可以使用ziparchiveminizip之类的东西来解压缩它。有几种开源解决方案。这两个过去曾为我工作过。很容易使用。

之后,使用解压缩的数据做任何你想做的事情就足够简单了。并进行一些大扫除并从手机中删除 zip 文件。

于 2013-04-11T18:15:23.587 回答