– 不会更改文件的内容

我试图写入一个文件“index.html”,我有我的资源。 我可以加载没有问题的文件,但我似乎无法写信给它。 什么都没有显示为一个错误,它根本不写。 该应用程序不会中止或任何事情,但是当我重新加载文件没有任何改变。

我写的代码:

NSBundle *thisBundle = [NSBundle bundleForClass:[self class]]; NSString *path = [thisBundle pathForResource:@"index" ofType:@"html"]; NSString *myString = [[NSString alloc] initWithFormat:@""]; [myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:NULL]; 

我的加载代码:

 [myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]]; 

我究竟做错了什么?

您现有的代码不会覆盖index.html文件的原因是应用程序无法覆盖其资源。 苹果的iOS应用程序编程指南特别指出:

这是包含应用程序本身的包目录。 不要写任何东西到这个目录。 为了防止篡改,bundle目录在安装时被签名。 写入此目录会更改签名并阻止您的应用程序再次启动。

相反,写入您的文档目录。 您可以像这样获取文档目录的path:

 NSString * docsDir = [NSHomeDirectory() stringByAppendingPathComponent:@"Documents"]; 

请注意,iOS上的NSHomeDirectory()简单地返回应用程序包的path。 一旦获得了文档目录的path,就可以写入资源,比如index.html,如下所示:

 NSString * path = [docsDir stringByAppendingPathComponent:@"index.html"]; [myString writeToFile:path atomically:YES encoding:NSUTF8StringEncoding error:nil]; 

请注意,我改变你的error:参数nil 。 这实际上不会影响任何东西,但通常使用nil来指示NULL Objective-C对象。

在执行操作之前,尝试将文件移动到文档目录

。H

 #import <Foundation/Foundation.h> @interface NSFileManager (NSFileManagerAdds) + (NSString*) copyResourceFileToDocuments:(NSString*)fileName withExt:(NSString*)fileExt; @end 

.M

 #import "NSFileManager + NSFileManagerAdds.h" @implementation NSFileManager (NSFileManagerAdds) + (NSString*) copyResourceFileToDocuments:(NSString*)fileName withExt:(NSString*)fileExt { //Look at documents for existing file NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES); NSString *documentsDirectory = [paths objectAtIndex:0]; NSString *path = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.%@", fileName, fileExt]]; NSFileManager* fileManager = [NSFileManager defaultManager]; if(![fileManager fileExistsAtPath:path]) { NSError *nError; [fileManager copyItemAtPath:[[NSBundle mainBundle] pathForResource:fileName ofType:fileExt] toPath:path error:&nError]; } return path; } @end 

最后你应该用这样的东西:

 [NSFileManager copyResourceFileToDocuments:@"index" withExt:@"html"];