如何将文件从URL复制到文档文件夹?

时间:2014-02-07 07:12:32

标签: iphone objective-c nsfilemanager

我需要从URL复制文本文件并将其覆盖/覆盖在我的应用程序的文档文件夹中,然后将其读回数据变量。 我有以下代码:

NSData *data;

//get docsDir
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docsDir=[paths objectAtIndex:0];

//get path to text.txt
NSString *filePath=[docsDir stringByAppendingPathComponent:@"text.txt"];

//copy file
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;

if([fileManager fileExistsAtPath:filePath]==YES){
    [fileManager removeItemAtPath:filePath error:&error];
}

NSString *urlText = @"http://www.abc.com/text.txt";

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
    NSFileManager *fileManager=[NSFileManager defaultManager];
    [fileManager copyItemAtPath:urlText toPath:filePath error:NULL];
}

//Load from file
NSString *myString=[[NSString alloc] initWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];

//convert string to data
data=[myString dataUsingEncoding:NSUTF8StringEncoding];

它以良好的方式构建和遵守但我无法在我的文档文件夹中创建text.txt文件,然后将任何内容传递给我的数据变量。 我是IOS和Xcode的新手,任何线索都将受到高度赞赏。谢谢!

2 个答案:

答案 0 :(得分:2)

NSFileManager只能处理本地路径。如果你给它一个URL,它将不会做任何有用的事情。

copyItemAtPath:toPath:error:采用错误参数。使用它,像这样:

NSError *error;
if (![fileManager copyItemAtPath:urlText toPath:filePath error:&error]) {
    NSLog(@"Error %@", error);
}

然后你会收到这个错误:

Error Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn’t be
completed. (Cocoa error 260.)" UserInfo=0x9a83c00 {NSFilePath=http://www.abc.com/text.txt, 
NSUnderlyingError=0x9a83b80 "The operation couldn’t be completed. 
No such file or directory"}

它无法读取http://www.abc.com/text.txt处的文件,因为它不是有效路径。


正如Sunny Shah所说,你必须首先在URL处获取对象:

NSString *urlText = @"http://www.abc.com/text.txt";

if (![[NSFileManager defaultManager] fileExistsAtPath:filePath])
{
    NSURL *url = [NSURL URLWithString:urlText];
    NSError *error;
    NSData *data = [[NSData alloc] initWithContentsOfURL:url options:0 error:&error];
    if (!data) { // check if download has failed
        NSLog(@"Error fetching file %@", error);
    }
    else {
        // successful download
        if (![data writeToFile:filePath options:NSDataWritingAtomic error:&error]) { // check if writing failed
            NSLog(@"Error writing file %@", error);
        }
        else {
            NSLog(@"File saved.");
        }
    }
}

始终检查错误!

答案 1 :(得分:1)

您应该从网址获取数据并使用 WriteToFile

 NSData *urlData = [NSData dataWithContentsOfURL: [NSURL URLWithString:urlText]];
    [urlData writeToFile:filePath atomically:YES];
相关问题