I’m trying to write to a file “index.html” that I have in my resources. I can load the file with no problem, but I can’t seem to write to it. Nothing is showing up as an error, it simply doesn’t write. The app doesn’t abort or anything, but when I re-load the file nothing has changed.
My writing code:
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];
My loading code:
[myWebView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"index" ofType:@"html"]isDirectory:NO]]];
What am I doing wrong?
The reason that your existing code doesn’t overwrite the
index.htmlfile is that an application can not overwrite its resources. Apple’s iOS Application Programming Guide specifically says:Instead, write to your documents directory. You can get the path to the documents directory like this:
Note that
NSHomeDirectory()on iOS simple returns the path to your application’s bundle. Once you have the path to the documents directory, you can write to a resource, let’s say index.html, as follows:Note that I changed your
error:parameter tonil. This will not actually affect anything, but it is common practice to usenilto indicate NULL Objective-C objects.