Saving images to a directory - objective-c

Hi I want to save an image to a directory, I pass the NSData and do what I think will save the file in a directory I create but the problem is that it doesn't save. This is what I have so far. Why doesn't the initWithContentsOfURL:encoding:error: work, it returns null but the other method I used works? The main problem is WRITETOURL which returns a 0 which i think means that the information wasn't stored properly, any tips?
NSFileManager *fm = [[NSFileManager alloc] init];
NSArray * directoryPaths = [fm URLsForDirectory:NSCachesDirectory inDomains:NSUserDomainMask];
NSLog(#"%#", directoryPaths);
NSURL* dirPath = nil;
dirPath = [[directoryPaths objectAtIndex:0] URLByAppendingPathComponent:[NSString stringWithFormat:#"photos.jpeg"]];
NSError* theError = nil;
[fm createDirectoryAtURL:dirPath withIntermediateDirectories:YES attributes:nil error:&theError];
UIImage* photoToStore = [UIImage imageWithData:photoToSave];
NSString *pathContainingPhoto = [[NSString alloc] initWithFormat:#"%#.jpeg", UIImageJPEGRepresentation(photoToStore, 1.0)];
NSError *error = nil;
BOOL OK = [pathContainingPhoto writeToURL:dirPath atomically:YES encoding:NSUTF8StringEncoding error:&error];
NSLog(#"OK = %d", OK); //Returns 0
NSLog(#"%#", dirPath);
//WHY DOESNT THIS VERSION WORK?
// NSString *pathToFile = [[NSString alloc] initWithContentsOfURL:dirPath encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", pathToFile);
NSString* pathToFile = [NSString stringWithContentsOfURL:dirPath encoding:nil error:nil];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:pathToFile error:nil];
NSLog(#"%#", dirContents);

Do like this and int count in .h file and set its intial value count = 0; in viewDidLoad:
NSString *stringPath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES)objectAtIndex:0]stringByAppendingPathComponent:[NSString stringWithFormat:#"Image_%d.png",count];
error = nil;
if (![[NSFileManager defaultManager] fileExistsAtPath:stringPath]) // removing item it already exuts
{
[[NSFileManager defaultManager] removeItemAtPath:stringPath error:&error];
}
if(photoToSave) // nsdata of image that u have
{
[photoToSave writeToFile:stringPath atomically:YES];
}
count++; // maintaining count of images

Related

How to get list of contents from folder using contentsOfDirectoryAtPath in cocoa?

I want to fetch all contents of the folder and add to a submenu of NSMenuItems.
For achieving this, I'm using code given below:
NSArray *dirContents = [[NSArray alloc]init];
dirContents=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:updated error:nil];
This code is working but only in one folder. Strange but it is true. I have tried the same code for other folders but it gives nil value in dirContents.
So how can I access the list of all the contents of a selected folder?
Try this to track the access error.
NSError *error;
NSArray *dirContents = [[NSArray alloc]init];
dirContents=[[NSFileManager defaultManager] contentsOfDirectoryAtPath:updated error:&error];
if(error){
NSLog(#"%#",error);
}
Make sure you use relative path to the directory, if the app is sandboxed, not absolute path.
NSURL *containerUrl =[[[NSFileManager defaultManager] containerURLForSecurityApplicationGroupIdentifier:#"Your.app.container.id"];
path = [[containerUrl URLByAppendingPathComponent:#"your/folder/path"] path];
+(NSArray*)allURLs:(NSURL*)url{
NSFileManager *fileManager = [NSFileManager defaultManager];
//NSURL *bundleURL = [[NSBundle mainBundle] bundleURL];
NSURL *bundleURL = url;
NSDirectoryEnumerator *enumerator = [fileManager enumeratorAtURL:bundleURL
includingPropertiesForKeys:#[NSURLNameKey, NSURLIsDirectoryKey]
options:NSDirectoryEnumerationSkipsHiddenFiles
errorHandler:^BOOL(NSURL *url, NSError *error)
{
NSLog(#"[Error] %# (%#)", error, url);
return url;
}];
NSMutableArray *mutableFileURLs = [NSMutableArray array];
for (NSURL *fileURL in enumerator) {
NSString *filename;
[fileURL getResourceValue:&filename forKey:NSURLNameKey error:nil];
NSNumber *isDirectory;
[fileURL getResourceValue:&isDirectory forKey:NSURLIsDirectoryKey error:nil];
// Skip directories with '_' prefix, for example
if ([filename hasPrefix:#"_"] && [isDirectory boolValue]) {
[enumerator skipDescendants];
continue;
}
if (![isDirectory boolValue]) {
[mutableFileURLs addObject:fileURL];
}
}
return mutableFileURLs;
}

writeToFile not properly saving data

I have data from a url (.m4a) and I am trying to save the file so I can edit it's metadata (change background image). The code below doesn't seem to work and I have no idea why. It is saving a file, but the file is empty.
_previewData = [NSMutableData dataWithContentsOfURL:[NSURL URLWithString:#"http://a281.phobos.apple.com/us/r1000/119/Music/v4/f1/7b/d6/f17bd6e3-55c0-b7e0-9863-bc522900e950/mzaf_5153970109972844579.aac.m4a"]];
NSArray *paths=NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentDirectory=[paths objectAtIndex:0];
NSString *path = [documentDirectory stringByAppendingPathComponent:[NSString stringWithFormat: #"file.mp4"]];
NSFileManager *filemanager;
filemanager = [NSFileManager defaultManager];
[_previewData writeToFile:path atomically:YES];
if ([filemanager fileExistsAtPath:path]) {
// Runs
NSLog(#"It worked");
}
NSLog(#"%#",path);
ANMovie* file = [[ANMovie alloc] initWithFile:path]; // or .mp4
NSData* jpegCover = UIImageJPEGRepresentation(artworkImage, 1.0);
_imageView.image = [UIImage imageWithData:jpegCover];
ANMetadata* metadata = [[ANMetadata alloc] init];
metadata.albumCover = [[ANMetadataImage alloc] initWithImageData:jpegCover type:ANMetadataImageTypeJPG];
[file setMovieMetadata:metadata];
[file close];
_previewData = [NSMutableData dataWithContentsOfFile:path];
UIPasteboard *pasteboard = [UIPasteboard generalPasteboard];
NSDictionary *imageItem=#{#"public.mpeg-4-audio":self.previewData};
NSDictionary *textItem=#{#"public.plain-text":self.linkData};
pasteboard.items=#[imageItem,textItem];

Using apples suggested code isnt excluding files from icloud backup

I have an app that has been rejected 3 times due to icloud backup issues. Apple have written back to say that I need to use there bit of code to exclude the files from being backed up. However this isnt working and i am at wits end.
Here is the code i've used
- (BOOL)downloadFile:(NSString *)fileURI targetFolder:(NSString *)targetFolder targetFilename:(NSString *) targetFilename{
#try{
NSError *error = nil;
NSURL *url = [NSURL URLWithString:fileURI];
if(![url setResourceValue:#"YES" forKey:NSURLIsExcludedFromBackupKey error:&error]){
NSLog(#"KCDM: Error excluding %# from backup %#", fileURI, error);
}else{
NSData *urlData = [NSData dataWithContentsOfURL:url];
if ( urlData )
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingString:targetFolder];
NSError *error = nil;
if(![[NSFileManager defaultManager] fileExistsAtPath:dataPath]){
[[NSFileManager defaultManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:&error];
}
NSString *filePath = [NSString stringWithFormat:#"%#/%#%#", documentsDirectory,targetFolder,targetFilename];
return [urlData writeToFile:filePath atomically:YES];
}
}
}
#catch(NSException * e){
NSLog(#"Error download: %#",e);
}
return false;
}
what am i doing wrong?
You try to set NSURLIsExcludedFromBackupKey for the http://-Url you download from the web. That won't work.
You have to set this key-value pair for the actual file that is saved on the device.
Additionally you are not supposed to set this value to the string #"YES", you must use a NSNumber object representing the boolean value YES.
For example:
NSString *filePath = [NSString stringWithFormat:#"%#/%#%#", documentsDirectory,targetFolder,targetFilename];
if ([urlData writeToFile:filePath atomically:YES]) {
// did write correctly
NSURL *fileURL = [NSURL fileURLWithPath:filePath];
if(![fileURL setResourceValue:#YES forKey:NSURLIsExcludedFromBackupKey error:&error]){
NSLog(#"KCDM: Error excluding %# from backup %#", fileURI, error);
return NO;
}
// could set NSURLIsExcludedFromBackupKey
return YES;
}
// could not write to file
return NO;

Reading fileModificationDate

How do I access the fileModificationDate
NSString *docsDir = [NSHomeDirectory() stringByAppendingPathComponent:
#"TempiPad"];
NSFileManager *localFileManager=[[NSFileManager alloc] init];
NSDirectoryEnumerator *dirEnum =
[localFileManager enumeratorAtPath:docsDir];
NSString *file;
// List all files in docsDir
while (file = [dirEnum nextObject]) {
NSLog(#"File = %#",file);
NSError *attributesError = nil;
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:file error:&attributesError];
NSString *fileModificationDate = [fileAttributes objectForKey:NSFileModificationDate];
NSLog(#"ModDate = %#",fileModificationDate);
}
}
This just outputs (null). Eventually I will want to compare the fileModificationDate for two files, so how will I do that?
IIRC, you need to append the filename to the directory path; something like:
while (file = [dirEnum nextObject]) {
NSLog(#"File = %#",file);
NSError *attributesError = nil;
file = [docsDir stringByAppendingPathComponent:file];
NSDictionary *fileAttributes = [[NSFileManager defaultManager] attributesOfItemAtPath:file error:&attributesError];
NSDate *fileModificationDate = [fileAttributes objectForKey:NSFileModificationDate];
NSLog(#"ModDate = %#",fileModificationDate);
}
}
And, as more tension said, NSFileModificationDate is an NSDate, not an NSString.
NSFileModificationDate returns an NSDate instance, not an NSString. See:
NSFileModificationDate

NSFileHandle fileHandleForWritingAtPath: return null!

my iPad app has a small download facility, for which I want to append the data using an NSFileHandle. The problem is the creation call only returns null file handles. What could be the problem? Here is the three lines of code that are supposed to create my file handle:
NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName];
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
I checked the file path, and I could see nothing wrong.
TYIA
fileHandleForWritingAtPath is not a “creation” call. The documentation explicitly states: “Return Value: The initialized file handle, or nil if no file exists at path” (emphasis added). If you wish to create the file if it does not exist, you’d have to use something like this:
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
if(output == nil) {
[[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil];
output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
}
If you want to append to the file if it already exists, use something like [output seekToEndOfFile]. Your complete code would then look as follows:
NSString *applicationDocumentsDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
self.finalPath = [applicationDocumentsDirectory stringByAppendingPathComponent: self.fileName];
NSFileHandle *output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
if(output == nil) {
[[NSFileManager defaultManager] createFileAtPath:self.finalPath contents:nil attributes:nil];
output = [NSFileHandle fileHandleForWritingAtPath:self.finalPath];
} else {
[output seekToEndOfFile];
}
Get documents directory path
+(NSURL *)getDocumentsDirectoryPath
{
return [[[NSFileManager defaultManager]URLsForDirectory:NSDocumentDirectory inDomains:NSUserDomainMask]lastObject];
}
Save text to end of the file
if file doesnt exist create it and write data
+(void)saveText:(NSString *)textTobeSaved atPath:(NSString*)fileName
{
NSString *filePath = [NSString stringWithFormat:#"%#.text",fileName];
NSString *path = [[self getDocumentsDirectoryPath].path
stringByAppendingPathComponent:filePath];
NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
if(fileHandler == nil) {
[[NSFileManager defaultManager] createFileAtPath:path contents:nil attributes:nil];
fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
} else {
textTobeSaved = [NSString stringWithFormat:#"\n-----------------------\n %#",textTobeSaved];
[fileHandler seekToEndOfFile];
}
[fileHandler writeData:[textTobeSaved dataUsingEncoding:NSUTF8StringEncoding]];
[fileHandler closeFile];
}
get text from file with specified filename
+(NSString *)getTextFromFilePath:(NSString *)fileName
{
NSString *filePath = [NSString stringWithFormat:#"%#.text",fileName];
NSString *path = [[self getDocumentsDirectoryPath].path
stringByAppendingPathComponent:filePath];
NSLog(#"%#",path);
if(path!=nil)
{
NSString *savedString = [NSString stringWithContentsOfFile:path encoding:NSUTF8StringEncoding error:nil];
return savedString;
}else{
return #"";
}
}
Delete file
+(void)deleteFile:(NSString *)fileName
{
NSString *filePath = [NSString stringWithFormat:#"%#.text",fileName];
NSString *path = [[self getDocumentsDirectoryPath].path
stringByAppendingPathComponent:filePath];
NSFileHandle *fileHandler = [NSFileHandle fileHandleForWritingAtPath:path];
if(fileHandler != nil) {
[[NSFileManager defaultManager]removeItemAtPath:path error:nil];
}
}