how to fix file writing issue into documents directory? - ios

I have implemented the logic of writing files into document directory.
NSData *pngData = UIImagePNGRepresentation([UIImage imageNamed:#"logo_icon_login.png"]);
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0];
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"];
if ([[NSFileManager defaultManager] isWritableFileAtPath:filePath])
{
[pngData writeToFile:filePath atomically:YES];
}
else
{
NSLog(#"Not writable.");
}
Now the problem is in some devices it says Not writable. Is there any permission should I need before writing files in the documents directory?

Create a folder namely images and than put the image inside. It could be root directory issue.
Try this:
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"images/image.png"];

Related

How to open locally saved PDF file in an Objective C

I'm trying to save PDF file to local storage.
I save the file this way and it seems to me that everything is fine.
//Get path directory
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//Create PDF_Documents directory
documentsDirectory = [documentsDirectory stringByAppendingPathComponent:#"PDF_Documents"];
[[NSFileManager defaultManager] createDirectoryAtPath:documentsDirectory withIntermediateDirectories:YES attributes:nil error:nil];
filePath = [NSString stringWithFormat:#"%#/%#", documentsDirectory, tastingName];
[tastingNotesData writeToFile:filePath atomically:YES];
This way I try to get the file
tastingPath = /var/mobile/Containers/Data/Application/4255D8B0-33F5-47AA-ABFA-CCC3691DA033/Documents/PDF_Documents/39e0afcdb56240c2a65ab9e136377b32.pdf;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *path = [documentsDirectory stringByAppendingPathComponent:[self.productModel.tastingPath lastPathComponent]];
NSData *data2 = [[NSFileManager defaultManager] contentsAtPath:path];
NSLog(#"tasting notes %#", data2);
At the end file will be displayed in the UIWebView.
What am I doing wrong?
The problem is simple. In your attempt to read the PDF file, you don't include the PDF_Documents part of the path. Or you are not appending the filename. Can't be 100% sure which part is wrong. It depends on what the value of [self.productModel.tastingPath lastPathComponent] is.

writeToFile working on iOS 7 not on iOS 6

I have been having an issue and I can't find anything about it.
I got some code to write files in the Documents folder with iOS. Checked the Apple documentation seems it's where I want to put the file for it to be available the next launch.
Here's the code I'm using:
- (void) writeToTextFile:(NSString *)logMessage inFile:(NSString *)fileName
{
//get the documents directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//make a file name to write the data to using the documents directory:
NSString *filePath = [NSString stringWithFormat:#"%#/%#.txt", documentsDirectory, fileName];
NSLog(#"TEST path: %#", filePath);
//save logMessage to the documents directory
[logMessage writeToFile:filePath atomically:YES encoding:NSStringEncodingConversionAllowLossy error:nil];
}
Now I'm using unit tests on this methods. It was working fine on the iOS 7.0.3 simulator, but when I switched to iOS 6.0 it doesn't work anymore.
In fact I found out that there was no Documents folder in "Application Support/iPhone Simulator/6.0/" but there's one in the 7.0.3 folder.
I can't really find any differences on how writing to a file should be handled between 6 and 7. Should I test if the folder exists then create it if it's not there?
This works for me
NSString *string = #"Text to save";
NSString *filePath = #"filerecord.txt";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *docDir = [paths objectAtIndex:0];
NSString *filePath = [docDir stringByAppendingPathComponent:filePath];
[string writeToFile:filePath atomically:YES];
UPDATE
Create Documents directory if not exists
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
if (![fileManager fileExistsAtPath:documentsDirectory]) {
[fileManager createDirectoryAtPath:documentsDirectory withIntermediateDirectories:NO attributes:nil error:&error];
}
NSString *string = #"Text to save";
NSString *filePath = #"filerecord.txt";
NSString *filePath = [documentsDirectory stringByAppendingPathComponent:filePath];
[string writeToFile:filePath atomically:YES];

Managing files and directories in an app's Documents directory

I am trying to work out how to manage files and directories in my app's Documents folder. I have been trying to make sense of the NSData class but without joy. I have managed to write an image to my Documents folder using the following code.
- (IBAction)writeImage:(id)sender
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *savedImagePath = [documentsDirectory stringByAppendingPathComponent:#"savedImage.png"];
UIImage *image = [UIImage imageNamed:#"Default.png"];
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
What I would like to know is how to create and delete directories and files. Can anyone point me to correct place to look? Thanks in advance.
For folder you can use:
[[NSFileManager defaultManager] createDirectoryAtURL:folder withIntermediateDirectories:YES attributes:nil error:&error];
It will create all folders at given path which is cool :)
The NSFileManager class enables you to perform many generic file-system operations and insulates an app from the underlying file system.
There is a class method in NSFileManager class called +defaultManager which always gives you same FileManager object or shared Object and most file operations can be performed using this shared file manager object.
You can write by avoiding overwriting your file if it already exists as below and can also check if the folder is writable or not.
NSString *imageName = #"Default.png";
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectoryPath = [paths objectAtIndex:0];
NSString *savedImagePath = [NSString stringWithFormat:#"%#/%#", documentsDirectoryPath, imageName];
// Write only if file does not exist.
if (![[NSFileManager defaultManager] fileExistsAtPath:savedImagePath]) {
NSData *imageData = UIImagePNGRepresentation(image);
[imageData writeToFile:savedImagePath atomically:NO];
}
// Check if folder is writable
NSString *folderPath = #"someFolderPath";
if ([[NSFileManager defaultManager] isWritableFileAtPath:folderPath]) {
NSLog(#"Folder is writable");
}else {
NSLog(#"Folder is not writable");
}

Why can't I save files to my iOS apps /Documents directory?

I am writing an app that can access the iOS root system, the user should be able to save files to his document directory. I am using this code to save the file to the document directory.
For Text:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:#"%#/%#", documentsDirectory, [self.filePath lastPathComponent]]
atomically:YES
encoding:NSUTF8StringEncoding error:nil];
For other files:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
[self.filePath writeToFile:[NSString stringWithFormat:#"%#/%#", documentsDirectory,[self.filePath lastPathComponent]]
atomically:YES];
My problem is I can save .txt files, but not other files, If I save for example .plist files with the save text methods, the contact is replaced by the directory path of the file. When I save a picture, or any other file it isn't readable. Is there a good method to save files without destroying them?
You're calling [self.filePath writeToFile:], thus writing the contents of the filePath variable to a file.
You should do something like:
[contents writeToFile:...]
Here you have an example of saving the image:
assuming you get the content of the image into NSData object:
NSData *pngData = UIImagePNGRepresentation(image);
then write it to a file:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsPath = [paths objectAtIndex:0]; //Get the docs directory
NSString *filePath = [documentsPath stringByAppendingPathComponent:#"image.png"]; //Add the file name
[pngData writeToFile:filePath atomically:YES]; //Write the file
Have a look into these questions for more detailed explanations:
Write a file on iOS
Save An Image To Application Documents Folder From UIView On IOS

Using Documents Directory for HTML Img

I'm trying to use the app's Documents directory to store images, and later access then with a webview with html. I tried using the /var/mobile/Applications/id/Documents but that didn't work. Is there a way to access those files in the webview?
For save image you have to download image like a NSMutableData in your Cache directory:
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES);
NSString *cachesDirectory = [paths objectAtIndex:0];
NSString* filePath = [NSString stringWithFormat:#"%#/imageTemp.png",cachesDirectory];
[imageData writeToFile:filePath atomically:YES];
After donwload you can move your image to your Document directory:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *arrayPath = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentPath = [arrayPath objectAtIndex:0];
NSString *cacheImagePath = filePath;
NSError *error;
[fileManager copyItemAtPath:cacheImagePath toPath:documentPath error:&error];
Turned out I missed a / so it should of been file:///var/mobile/Applications/id/Documents then it worked.

Resources