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

Tal*_*Siu 5 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];
Run Code Online (Sandbox Code Playgroud)

它以良好的方式构建和遵循,但是我无法在文档文件夹中创建text.txt文件,然后将任何内容传递给我的数据变量。我是IOS和Xcode的新手,任何线索将不胜感激。谢谢!!

Mat*_*uch 2

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

\n\n

copyItemAtPath:toPath:error:接受一个错误参数。使用它,像这样:

\n\n
NSError *error;\nif (![fileManager copyItemAtPath:urlText toPath:filePath error:&error]) {\n    NSLog(@"Error %@", error);\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

然后你会得到这个错误:

\n\n
Error Error Domain=NSCocoaErrorDomain Code=260 "The operation couldn\xe2\x80\x99t be\ncompleted. (Cocoa error 260.)" UserInfo=0x9a83c00 {NSFilePath=http://www.abc.com/text.txt, \nNSUnderlyingError=0x9a83b80 "The operation couldn\xe2\x80\x99t be completed. \nNo such file or directory"}\n
Run Code Online (Sandbox Code Playgroud)\n\n

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

\n\n
\n\n

正如 Sunny Shah 所说,没有任何解释,您必须首先从 URL 获取对象:

\n\n
NSString *urlText = @"http://www.abc.com/text.txt";\n\nif (![[NSFileManager defaultManager] fileExistsAtPath:filePath])\n{\n    NSURL *url = [NSURL URLWithString:urlText];\n    NSError *error;\n    NSData *data = [[NSData alloc] initWithContentsOfURL:url options:0 error:&error];\n    if (!data) { // check if download has failed\n        NSLog(@"Error fetching file %@", error);\n    }\n    else {\n        // successful download\n        if (![data writeToFile:filePath options:NSDataWritingAtomic error:&error]) { // check if writing failed\n            NSLog(@"Error writing file %@", error);\n        }\n        else {\n            NSLog(@"File saved.");\n        }\n    }\n}\n
Run Code Online (Sandbox Code Playgroud)\n\n

经常检查是否有错误!

\n