我使用NSURLConnection方法下载文件,但是当我尝试保存并加载数据时,存档已损坏
这是我的代码,感谢任何帮助
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);
}
和这种方法创建文件。但是,当我尝试打开IPHONE模拟器文件夹时,存档被破坏了 / 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");
}
}
答案 0 :(得分:1)
你需要撤销一些陈述:
// this first
if (data2==nil) {
data2 = [[NSMutableData alloc] initWithCapacity:[filesize floatValue]];
}
// Then this
[data2 appendData:recievedData];