I am trying to dowload simultaneously several files from my own server while using this code :
- (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]];
}
}
I have 3 pictures , pic1.png , pic2.png and pic3.png. Now if i run this code, the app will only save one corrupted file named pic3.png and automatically crashes. I need to download all three files, any pointers where i am going wrong?