Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/ios/101.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ios 如何在本地缓存中关闭并存储文本文件_Ios_Objective C - Fatal编程技术网

Ios 如何在本地缓存中关闭并存储文本文件

Ios 如何在本地缓存中关闭并存储文本文件,ios,objective-c,Ios,Objective C,我正在开发一个IOS应用程序。从URL下载数据并保存在本地缓存中。但我正在使用此代码。第一次数据可以存储在本地缓存中,也可以读取文本字段。但是在模拟器上删除应用程序并运行,然后再次将文本文件存储在本地缓存中。文件无法存储。非常感谢任何帮助或建议。提前谢谢 NSURL *url = [NSURL URLWithString:@"http://webapp.opaxweb.net/books/"]; NSData *data_file = [[NSData alloc]initWithContent

我正在开发一个IOS应用程序。从URL下载数据并保存在本地缓存中。但我正在使用此代码。第一次数据可以存储在本地缓存中,也可以读取文本字段。但是在模拟器上删除应用程序并运行,然后再次将文本文件存储在本地缓存中。文件无法存储。非常感谢任何帮助或建议。提前谢谢

NSURL *url = [NSURL URLWithString:@"http://webapp.opaxweb.net/books/"];
NSData *data_file = [[NSData alloc]initWithContentsOfURL:url];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle]  resourcePath] stringByDeletingLastPathComponent]stringByAppendingPathComponent:@"Documents"]];
NSString *filepath = [resourceDocPath stringByAppendingPathComponent:@"gurugranthsahib.txt"];
[data_file writeToFile:filepath atomically:YES];

NSLog(@"%@",filepath);
NSString* content = [NSString stringWithContentsOfFile:filepath
                                              encoding:NSUTF8StringEncoding
                                                 error:NULL];

iOS不允许写入应用程序包

通常,数据会写入文档目录:

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths firstObject];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:fileName];
注:

更好的做法是使用具有错误参数的方法调用,以便在出现错误时可以检查错误。在这种情况下,您可以使用:

NSError *error;
BOOL status = [string writeToFile:filePath options:NSDataWritingAtomic error:&error];
if (status == NO) {
    NSLog(@"error: %@", error)
}