我正在尝试在使用此代码时同时从我自己的服务器下载几个文件:
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// create
[[NSFileManager defaultManager] createFileAtPath:strFilePath contents:nil attributes:nil];
_file = [NSFileHandle fileHandleForUpdatingAtPath:strFilePath];// read more about file handle
if (_file) {
[_file seekToEndOfFile];
}
}
- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)receivedata
{
//write each data received
if( receivedata != nil){
if (_file) {
[_file seekToEndOfFile];
}
[_file writeData:receivedata];
}
}
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
//close file after finish getting data;
[_file closeFile];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error
{
//do something when downloading failed
}
- (IBAction)downloadFromServer:(id)sender {
NSLog(@"File now being downloaded");
while (i<=3) {
NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
NSURL *strFileURL =[NSURL URLWithString:[NSString stringWithFormat:@"SomePath/pic%d.png", i]];
[request setURL:strFileURL];
NSURLConnection *conection = [[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO];
[conection start];
strFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"pic%d.png", i]];
}
}
我有 3 张图片,pic1.png、pic2.png 和 pic3.png。现在,如果我运行此代码,该应用程序将只保存一个名为 pic3.png 的损坏文件并自动崩溃。我需要下载所有三个文件,我哪里出错了?