Reputation: 1973
I download a file with NSURLConnection methods, but when I try to save and load data the archive is corrupted
This is my code any help is appreciated
NSNumber *filesize;
NSMutableData *data2;
- (void)connection: (NSURLConnection*) connection didReceiveResponse: (NSHTTPURLResponse*) response
{
[data2 setLength:0];
if ([response expectedContentLength] == NSURLResponseUnknownLength) {
// unknown content size
filesize = @0;
}
else {
filesize = [NSNumber numberWithLongLong:[response expectedContentLength]];
NSLog(@"%@",filesize);
}
}
- (void)connection:(NSURLConnection *)theConnection didReceiveData:(NSData *)recievedData {
[data2 appendData:recievedData];
if (data2==nil) {
data2 = [[NSMutableData alloc] initWithCapacity:[filesize floatValue]];
}
NSNumber *resourceLength = [NSNumber numberWithUnsignedInteger:[data2 length]]; //MAGIC
float progress = [resourceLength floatValue] / [filesize floatValue];
progressBar.progress = progress;
NSLog(@"%f",progress);
}
AND THIS METHOD CREATE THE FILE. BUT WHEN I TRY TO OPEN THE IPHONE SIMULATOR FOLDER THE ARCHIVE IS CORRUPTED /Users/astramex19/Library/Application Support/iPhone Simulator/6.1/Applications/5D2E5AEB-6C27-43A9-9335-207A20A10F13/Documents/db.sqlite
- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
NSString *fileName = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents/db.sqlite"];
// BOOL filecreationSuccess = [fileManager createFileAtPath:fileName contents:data2 attributes:nil];
BOOL filecreationSuccess = [[NSFileManager defaultManager] createFileAtPath:fileName contents:data2 attributes:nil];
if(filecreationSuccess == NO){
NSLog(@"Failed to create the file");
}
}
Upvotes: 1
Views: 189
Reputation: 41642
You need to reverse some statements:
// this first
if (data2==nil) {
data2 = [[NSMutableData alloc] initWithCapacity:[filesize floatValue]];
}
// Then this
[data2 appendData:recievedData];
Upvotes: 1