将存档保存到Documents文件夹

时间:2012-12-07 15:56:49

标签: ios xcode download

以下是我下载档案并将其保存到我的Documents文件夹的代码:

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目录中的子文件夹已创建,但它是空的。

由于

1 个答案:

答案 0 :(得分:1)

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

dataPath是您创建的目录。您需要在该路径中附加文件名,然后将文件写入该完整路径(使用文件名)。