1

我使用 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 SIMULATOR 文件夹时,存档已损坏 /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");

    }

}
4

1 回答 1

1

您需要颠倒一些陈述:

// this first
if (data2==nil) {
    data2 = [[NSMutableData alloc] initWithCapacity:[filesize floatValue]];
}
// Then this
[data2 appendData:recievedData];
于 2013-08-22T21:48:15.317 回答