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

4.1k views Asked by At

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?

2

There are 2 answers

2
Kris On BEST ANSWER

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

0
iHunter On

You're calling [self.filePath writeToFile:], thus writing the contents of the filePath variable to a file.

You should do something like:

[contents writeToFile:...]