ios claims the file has been written to, but the changes never actually save, as if they remain in buffer. Do I have to flush or something?
- (void)viewDidLoad
{
[super viewDidLoad];
NSString *myFilePath = [[NSBundle mainBundle]
pathForResource:#"MyFile"
ofType:#"txt"];
NSLog(#"\n\nPath = \n%#", myFilePath);
NSString *myFileContents = [NSString stringWithContentsOfFile:myFilePath
encoding:NSUTF8StringEncoding
error:nil];
NSLog(#"\n\nContents = \n%#", myFileContents);
[#"This line will be written to file" writeToFile:myFilePath
atomically:YES encoding:NSUTF8StringEncoding error:nil];
NSString *changedContents = [NSString stringWithContentsOfFile:myFilePath
encoding:NSUTF8StringEncoding
error:nil];
NSLog(#"\n\nChanged Contents = \n%#", changedContents);
}
Output:
Path =
/Users/hamzeh/Library/Application Support/iPhone Simulator/5.1/Applications/2B318687-A745-4CD9-85BA-52A01AB76F6E/savepersistentdata_tutorial.app/MyFile.txt
Contents =
This is a text file.
The file will be displayed on the iPhone.
That is all for now.
Changed Contents =
This line will be written to file
This is the output I get every time I run, so the changes don't actually get written to the file.
Thanks for the help.
You can't edit files in your main bundle. You have to first save the file to the applications documents folder then make any changes.
Here's some code to maybe fix your issue:
First save the text to a directory you create:
NSString *myFilePath = [[NSBundle mainBundle]
pathForResource:#"MyFile"
ofType:#"txt"];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *directory = [NSString stringWithFormat:#"%#/Some_Directory", [paths objectAtIndex:0]];
// Check if the directory already exists
if (![[NSFileManager defaultManager] fileExistsAtPath:directory]) {
// Directory does not exist so create it
[[NSFileManager defaultManager] createDirectoryAtPath:directory withIntermediateDirectories:YES attributes:nil error:nil];
}
NSData *data = [[NSData dataWithContentsOfFile:myFilePath] retain];
NSString *filePath = [[directory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#", [myFilePath lastPathComponent]]] retain];
NSError *error = nil;
if (![data writeToFile:filePath options:NSDataWritingFileProtectionNone error:&error]) {
[data writeToFile:filePath atomically:NO];
}
[data release];
[filePath release];
Use NO parameter
[#"This line will be written to file" writeToFile:myFilePath atomically:NO encoding:NSUTF8StringEncoding error:nil];
iOS docs says
(BOOL)useAuxiliaryFile
If YES, the receiver is written to an auxiliary file, and then the auxiliary file is renamed to path. If NO, the receiver is written directly to path. The YES option guarantees that path, if it exists at all, won’t be corrupted even if the system should crash during writing.
You can not write file on main bundle, because resource bundle are read only. You can also check return of writeToFile method. Which returns false if you deploy it on device.
Related
I want to generate a print preview of a web page and save it to an PDF file.
i tried stringByEvaluatingJavaScriptFromString:#"document.body.scrollHeight";
and
stringByEvaluatingJavaScriptFromString:#"document.body.scrollWidth";
functions for finding the height and width but problem with this is the java script program stops after 10 second..
I want to use default print option that is used for airPrint, but i don't want that to print.
I just want to save the print preview in PDF.
Please any one help me..
NSString *webServiceUrlString =#"https://www.google.com"; //Google.com is for example use your url
NSData *pdfData = [[NSData alloc]initWithContentsOfURL:[NSURL URLWithString:webServiceUrlString]];
NSString *resourceDocPath = [[NSString alloc] initWithString:[[[[NSBundle mainBundle] resourcePath] stringByDeletingLastPathComponent] stringByAppendingPathComponent:#"Documents"]];
NSFileManager *fm = [NSFileManager defaultManager];
NSError *error = nil;
for (NSString *file in [fm contentsOfDirectoryAtPath:resourceDocPath error:&error]) {
BOOL success = [fm removeItemAtPath:[NSString stringWithFormat:#"%#/%#", resourceDocPath, file] error:&error];
if (!success || error) {
}
}
NSString* fileName = #"Your File Name.pdf";
NSString *filePath = [resourceDocPath stringByAppendingPathComponent:fileName];
[pdfData writeToFile:filePath atomically:YES];
You can use UIGraphicsBeginPDFContextToFile to create a PDF file from your webpage content.
Check out the following tutorial.MAKING A PDF FROM A UIWEBVIEW
I have a plist file in my main app bundle that I want to update via my app. Here is the code I'm using, the problem is that the plist doesn't seem to be getting updated. Is my code incorrect or is there another issue?
// Data
NSMutableDictionary *data = [[NSMutableDictionary alloc] init];
[data setObject:self.someValue forKey:#"Root"];
// Save the logs
NSString *filepath = [[NSBundle mainBundle] pathForResource:#"MyFile" ofType:#"plist"];
[data writeToFile:filepath atomically:YES];
Please can someone help me out?
IOS restricts writing to bundled files. If you want a writable plist, you need to copy it to your app's Documents folder and write to it there.
Here's how I'm doing it in one of my apps
//get file paths
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *documentPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [documentPaths objectAtIndex:0];
NSString *documentPlistPath = [documentsDirectory stringByAppendingPathComponent:#"document.plist"];
NSString *bundlePath = [[NSBundle mainBundle] bundlePath];
NSString *bundlePlistPath = [bundlePath stringByAppendingPathComponent:#"bundle.plist"];
//if file exists in the documents directory, get it
if([fileManager fileExistsAtPath:documentPlistPath]){
NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
return documentDict;
}
//if file does not exist, create it from existing plist
else {
NSError *error;
BOOL success = [fileManager copyItemAtPath:bundlePlistPath toPath:documentPlistPath error:&error];
if (success) {
NSMutableDictionary *documentDict = [NSMutableDictionary dictionaryWithContentsOfFile:documentPlistPath];
return documentDict;
}
return nil;
}
Hope this helps
Im new to Iphone development, I have locally saved one xml file and showing the details by using NSXmlParser(Which is stored in Resource folder). But, now i want to download new xml from url(from client side) and need to store that new xml file in Cache directory and also delete the xml file from resource folder. but i did not parse the new xml file from cache directory, How can i parse the new xml file from cache directory? Any one know this, please help me
I've actually just recently written this functionality for one of my projects. I'll share the code i used to do to save and write the XML file to my cache.
- (NSString *)XMLCacheFilePath
{
NSString *directory = #"/Library/Caches/XML/";
NSString *fileName = [#"file" stringByAppendingPathExtension:#"xml"];
// Setup directory path
NSString *homeDirectoryPath = NSHomeDirectory();
NSString *unexpandedDirectoryPath = [homeDirectoryPath stringByAppendingString:directory];
NSString *directoryPath = [NSString pathWithComponents:[NSArray arrayWithObjects:
[NSString stringWithString:[unexpandedDirectoryPath stringByExpandingTildeInPath]],
nil]];
// Setup file path
NSString *unexpandedFilePath = [directoryPath stringByAppendingPathComponent:fileName];
NSString *filePath = [NSString pathWithComponents:[NSArray arrayWithObjects:
[NSString stringWithString:[unexpandedFilePath stringByExpandingTildeInPath]],
nil]];
if (![[NSFileManager defaultManager] fileExistsAtPath:directoryPath isDirectory:nil]) {
NSError *error = [[NSError alloc] init];
[[NSFileManager defaultManager] createDirectoryAtPath:directoryPath
withIntermediateDirectories:YES
attributes:nil
error:&error];
}
return filePath;
}
- (void)saveXMLStringToDisk:(NSString *)xmlString
{
NSError *error;
[xmlString writeToFile:self.XMLCacheFilePath
atomically:YES
encoding:NSUTF8StringEncoding
error:&error];
}
- (NSString *)XMLStringFromDisk
{
NSString *XMLString = [NSString stringWithContentsOfFile:self.XMLCacheFilePath
encoding:NSUTF8StringEncoding
error:nil];
return XMLString;
}
In my work, I just want to read a downloaded PDF in iphone device
At first, I tried to use the "bundleRoot" directory, it is work in simulator but not on device. Now, I just test in simulator for Directory of Document or Cache.
How can I get a writable path on the iPhone?
After I read the above topic,
I have tried using Directory of Document or Cache.
Here is my code in finding the writable path
/******************************************************************************/
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
BOOL isDir = NO;
NSError *error;
if (! [[NSFileManager defaultManager] fileExistsAtPath:cachePath isDirectory:&isDir] && isDir == NO) {
[[NSFileManager defaultManager] createDirectoryAtPath:cachePath withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *path_to_file = [cachePath stringByAppendingPathComponent:#"testing6.pdf"];
/******************************************************************************/
I can find the downloaded file and get the size in this directory,but I cannot read the file by using the following code :
pdf = CGPDFDocumentCreateWithURL((CFURLRef)pdfURL);
page = CGPDFDocumentGetPage(pdf, 1);
CGPDFPageRetain(page);
CGRect pageRect = CGPDFPageGetBoxRect(page, kCGPDFMediaBox);
The return pageRect.size.width is 0
After I print out the download and retrieve file path also are :
/Users/ITDEV/Library/Application Support/iPhone Simulator/4.3.2/Applications/806ED359-70F8-4C07-996F-6AFC959B3FC7/Library/Caches/testing6.pdf
Anyone can help me pls?
If all other answers won't work then try using NSBundle as below:
NSString *path = [[NSBundle mainBundle] pathForResource:#"myfilename" ofType:#"pdf"];
NSLog("path : %#",path);
Same problem i faced and i found that my plist file was not in Documents directory but instead it shows me path to my app and then it shows MYAppName.app/myPlist.plist file. This means that the app file includes my plist file in its own bundle i.e. MainBundle.
You can read the file in UIWebView.
And By using below code you can open the file.
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachePath = [paths objectAtIndex:0];
BOOL isDir = NO;
NSError *error;
if (! [[NSFileManager defaultManager] fileExistsAtPath:cachePath isDirectory:&isDir] && isDir == NO) {
[[NSFileManager defaultManager] createDirectoryAtPath:cachePath withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *path_to_file = [cachePath stringByAppendingPathComponent:#"testing6.pdf"];
NSURL *targetURL = [NSURL fileURLWithPath:path_to_file];
NSURLRequest *request = [NSURLRequest requestWithURL:targetURL];
[YourWebViewName loadRequest:request];
Don't Forget to connect the IBOutlet of your webview with nib file's UIWebview.
I'm trying to copy a file from my application bundle to my app's documents directory. I'm getting an error, "Cocoa Error 262". What am I doing wrong? Here's my code:
NSURL *storeURL = [[self applicationDocumentsDirectory] URLByAppendingPathComponent:#"CoreData.sqlite"];
NSURL *initialURL = [NSURL URLWithString:[[NSBundle mainBundle] pathForResource:#"CoreData" ofType:#"sqlite"]];
NSError *error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:[initialURL absoluteString]]) {
NSLog(#"Original does not exist. \nPath: %#", [initialURL absoluteString]);
}
if (![[NSFileManager defaultManager] fileExistsAtPath:[storeURL absoluteString]]) {
NSLog(#"Destination file does not exist. \nPath: %#", [storeURL absoluteString]);
[[NSFileManager defaultManager] copyItemAtURL:initialURL toURL:storeURL error:&error];
NSLog(#"Error: %#", [error description]);
}
The problem is you're initializing a URL with a plain old file path.
NSURL *initialURL =
[NSURL URLWithString:[[NSBundle mainBundle] pathForResource:#"CoreData"
ofType:#"sqlite"]];
Use [NSURL fileURLWithPath:] instead.
The error you are getting is
NSFileReadUnsupportedSchemeError
Read error because the specified URL scheme is unsupported
which I believe would mean one of your paths is not forming correctly. perhaps write these paths to the log and see if they are coming out as you expect them to.
I've solved the problem, although to be honest, I'm not sure what it was. I have to go over the working code again, but here it is:
NSError *error = nil;
NSString *documentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:[NSString stringWithFormat:#"%#.%#", #"CoreData", #"sqlite"]];
//if file does not exist in document directory, gets original from mainbundle and copies it to documents.
if (![[NSFileManager defaultManager] fileExistsAtPath:filePath]) {
NSString *defaultFilePath = [[NSBundle mainBundle] pathForResource:#"CoreData" ofType:#"sqlite"];
[[NSFileManager defaultManager] copyItemAtPath:defaultFilePath toPath:filePath error:&error];
if (error != nil) {
NSLog(#"Error: %#", error);
}
}
Edit:
I suspect that the path to the application directory was incorrect, given that the body of the generated applicationDocumentsDirectory looks different than the method used for the value of the documentsDorectory variable shown above.
Error 262 is defined in FoundationErrors.h to be NSFileReadUnsupportedSchemeError.
I'd suggest that you use NSLog() to write out the literal values of the two URLs that you're using and make sure that they are file:// URLs and that they look complete.