0
我需要從服務器下載一些文件。什麼是最好的方式來做到這一點? 所有文檔都存儲在NSMutableArray中,每個文檔都有兩個文件 - 文檔本身及其更改日誌。所以我做的是:iPhone - 如何下載大量的文件
- (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];
}
}
而我的問題是,只有最後一個文件被下載。任何建議,我做錯了什麼? 在此先感謝您的幫助!
請問你能寫一個例子嗎? – Oleg
或者你知道更好的方式來下載文件列表嗎? – Oleg
好吧,而不是「downloadConnection」是一個NSURLConnection,你將它設置爲NSMutableArray。在你的「downloadSingleDocument」方法中,通過使用[downloadConnection addObject:theConnectionVar]將新創建的NSURLConnection實例添加到列表中。在NSURLConnection委託方法(didReceiveResponse等)中循環遍歷downloadConnection-Array中的所有條目,並檢查每個條目是否與條目的param給出的connection-var匹配。如果是這樣,這是匹配的連接,你可以像以前一樣進步。 – TRD