保存归档的文档文件夹

问题描述:

下面是代码我有下载的存档,并保存到我的文档文件夹:保存归档的文档文件夹

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:[NSURL URLWithString:resource] cachePolicy:NSURLRequestReloadIgnoringLocalAndRemoteCacheData timeoutInterval:10]; 

NSData *receivedData; 
NSURLResponse *requestResponse; 
NSError *requestError; 

int i = 3; 

while (i) //Try 3 times 
{ 
    receivedData = [NSURLConnection sendSynchronousRequest:request returningResponse:&requestResponse error:&requestError]; 

    if (receivedData) 
    { 
     i = 0; 
    } 
    else i--; 
} 

if (!receivedData) 
{ 
    NSLog(@"************************************************"); 
    NSLog(@"** Error downloading data for resource : %@ **", resource); 
    NSLog(@"************************************************"); 
} 
else 
{ 
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); 
    NSString *documentsDirectory = [paths objectAtIndex:0]; //Get documents folder 
    NSString *dataPath; 
    dataPath = [documentsDirectory stringByAppendingPathComponent:LIST_FOLDER]; 
    NSError *documentError; 

    if (![[NSFileManager defaultManager] fileExistsAtPath:dataPath]) //Create folder 
    { 
     [[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&documentError]; 
    } 

    NSLog(@"saveError = %@", documentError); //Prints out null so no problem here 

    NSError *writeError; 

    [receivedData writeToFile:dataPath options:NSDataWritingAtomic error:&writeError]; 

    NSLog(@"write error = %@", writeError); 

最后的NSLog打印出以下内容并不会保存归档:

Error Domain=NSCocoaErrorDomain Code=512 "The operation couldn’t be completed. (Cocoa error 512.)" "The operation couldn’t be completed. Is a directory"} 

在Documents目录中的子文件夹被创建,但它是空的。

谢谢

您正试图将数据写入文件夹。您需要将其写入文件夹中的文件。

dataPath是你创建的目录。您需要将文件名添加到路径,然后将文件写入到完整路径(含文件名)。

+0

我想将文件保存他们的名字(不一定是同一个),我不能让他们从档案? –

+0

另外,我知道NSURLConnection的可以下载它们时我的文档解压缩文件。我怎样才能做到这一点? –