gpt4 book ai didi

iPhone - 如何下载大量文件

转载 作者:行者123 更新时间:2023-11-29 04:39:26 24 4
gpt4 key购买 nike

我需要从服务器下载一些文件。最好的方法是什么?所有文档都存储在 NSMutableArray 中,每个文档都有两个文件 - 文档本身及其更改日志。所以我要做的是:

- (void)downloadDocuments:(int)docNumber
{
NSString *urlString;
NSURL *url;
for (int i=0; i<[items count]; i++) {
[progressBar setProgress:((float)i/[items count]) animated:YES];
urlString = [[items objectAtIndex:i] docUrl];
url = [[NSURL alloc] initWithString:[urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
[self downloadSingleDocument:url];
urlString = [[items objectAtIndex:i] changeLogUrl];
url = [[NSURL alloc] initWithString:[urlString stringByAddingPercentEscapesUsingEncoding: NSUTF8StringEncoding]];
[self downloadSingleDocument:url];
}
urlString = nil;
url = nil;
[self dismissModalViewControllerAnimated:YES];
}

- (void)downloadSingleDocument:(NSURL *)url
{
NSMutableURLRequest *req = [NSMutableURLRequest requestWithURL:url];
[req addValue:@"Basic XXXXXXX=" forHTTPHeaderField:@"Authorization"];
downloadConnection = [[NSURLConnection alloc] initWithRequest:req delegate:self startImmediately:YES];
}

- (void)connection:(NSURLConnection *)conn didReceiveResponse:(NSURLResponse *)response
{
if (conn == downloadConnection) {
NSString *filename = [[conn.originalRequest.URL absoluteString] lastPathComponent];
filename = [filename stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];

filePath = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:filename];
[[NSFileManager defaultManager] createFileAtPath:filePath contents:nil attributes:nil];

file = [[NSFileHandle fileHandleForUpdatingAtPath:filePath] retain];
if (file)
{
[file seekToEndOfFile];
}
}

}


- (void)connection:(NSURLConnection *)conn didReceiveData:(NSData *)data
{
if (conn == downloadConnection) {
if (file) {
[file seekToEndOfFile];
}
[file writeData:data];
}

}


- (void)connectionDidFinishLoading:(NSURLConnection *)conn
{

if (conn==downloadConnection) {
[file closeFile];
}
}

我的问题是只下载了最后一个文件。关于我做错了什么有什么建议吗?预先感谢您的帮助!

最佳答案

问题在于您使用 NSURLConnection 的新实例“覆盖”循环中的成员变量“downloadConnection”(通过方法调用 downloadSingleDocument)。这样做会导致 didReceiveResponse、didReceiveData 和 connectionDidFinish 方法中的 if 语句仅在最新创建的连接时评估为 true。尝试使用连接列表来避免这种情况。

关于iPhone - 如何下载大量文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10615323/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com