2013-08-22 153 views
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模拟器文件夹中的存档文件损坏 /用户/ astramex19 /库/应用程序支持/ iPhone模拟器/ 6.1 /应用/ 5D2E5AEB-6C27-43A9-9335-207A20A10F13 /文档/ 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"); 

    } 

} 

回答

1

你需要扭转一些语句:

// this first 
if (data2==nil) { 
    data2 = [[NSMutableData alloc] initWithCapacity:[filesize floatValue]]; 
} 
// Then this 
[data2 appendData:recievedData]; 
+0

是的,这是我的错误在我的应用程序 您的代码工作得很好。非常感谢!!! = d – Fabio