我需要从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的新手,任何线索将不胜感激。谢谢!!