I want to create a NSArray from my app sandbox's documentsDirectory's includes. It includes so many files, but my array will only be by the ones ends with .MOV.
Can you help me?
Thank you!
There are a couple of options using the NSFileManager.
NSString *path = #"<dir_path>";
//Option 1 using directory enumerator
NSDirectoryEnumerator *direnum = [[NSFileManager defaultManager] enumeratorAtPath:path];
NSMutableArray *movfiles = [NSMutableArray array];
while(NSString *file = [direnum nextObject])
{
if([[file pathExtension] isEqualToString:#"MOV"])
[movfiles addObject:movfiles];
}
//Option 2 case insensitive using a predicate
NSError *error;
NSArray *dircontents = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:path error:&error];
if(error)
{
//Handle error
}
else
{
dircontents = [dircontents filteredArrayUsingPredicate:
[NSPredicate predicateWithFormat:#"pathExtension ==[c] %#", #"mov"]];
}
Related
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;
}
I'm trying to access in ~/Library/Preferences/ but my code doesn't work.
NSString *resPath = #"~/Library/Preferences/";
NSError *error = nil;
NSArray *filenames = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:resPath error:&error];
if (!error)
{
for (NSString * filename in filenames)
{
NSLog(#"%#", filename);
}
}
Maybe I should ask for some permission.. Any idea?
You need to use NSString method: stringByExpandingTildeInPath to expand the ~ into the full path.
NSString *resPath = [#"~/Library/Preferences/" stringByExpandingTildeInPath];
NSLog(#"resPath: %#", resPath);
Output:
resPath: /Volumes/User/me/Library/Preferences
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;
I have a multiple strings I would like to write to one plist using objective c. Can anyone please tell me exactly how to do this? I appreciate it
As H2CO3 hinted, you could use NSArray's writeToFile:atomically: method.
For example:
NSArray *arr = #[
#"my first string",
#"my second string",
#"and the last one"
];
[arr writeToFile:#"./out.plist" atomically:NO]; // Or YES depending on your needs
Here's one possibility:
// Create the path that you want to write your plist to.
NSError *error = nil;
NSURL *documentsURL = [[NSFileManager defaultManager] URLForDirectory:NSDocumentDirectory inDomain:NSUserDomainMask appropriateForURL:nil create:YES error:&error];
if (documentsURL == nil) {
NSLog(#"Error finding user documents in directory: %#", [error localizedDescription]);
return nil;
}
NSString *path = [[documentsURL path] stringByAppendingPathComponent:#"YourFile.plist"];
// Populate your strings and save to the plist specified in the above path.
NSString *kRoot = #"kRoot";
NSMutableDictionary *tempDict = [NSMutableDictionary dictionary];
tempDict[kRoot] = [NSMutableArray array];
[tempDict[kRoot] addObject:#"String 1"];
[tempDict[kRoot] addObject:#"String 2"];
[tempDict[kRoot] addObject:#"String 3"];
// Etc, add all your strings
if (![tempDict writeToFile:path atomically:YES])
{
NSLog(#"Error writing data to path %#", path);
}
I am trying to convert a .m file to string. I will search for files in a folder and then want to use each of its contents as a string. This is the code I am using:
- (IBAction)searchAction:(id)sender {
NSFileManager *fm = [NSFileManager defaultManager];
NSArray *dirContents = [fm contentsOfDirectoryAtPath:folderLabel.stringValue error:nil];
NSPredicate *fltr = [NSPredicate predicateWithFormat:#"self ENDSWITH '.m'"];
NSArray *onlyMs = [dirContents filteredArrayUsingPredicate:fltr];
for (int i=0; i<[onlyMs count]; i++) {
NSString* text = [[NSString alloc] initWithContentsOfFile:[onlyMs objectAtIndex:i]
encoding:NSUTF8StringEncoding
error:nil];
NSLog(#"string: %#", text);
}
}
2013-02-13 02:38:05.700 LocalizedStringSearch[19001:303] string: (null)
Except here, all the log is returning is null even though it will find all the .m file correctly.
Anyone know what I'm doing wrong?
Thanks a lot!
I think contentsOfDirectoryAtPath: gives you an array of filenames only, not full path names, so you need to prepend the path before you open files. EDIT: I think I might be confusing that with enumeratorAtPath:... if so continue using the filenames you have rather than appending them to the original folder name.
Here's an example (untested):
NSString *fullPath = [folderLabel.stringValue stringByAppendingPathComponent:[onlyMs objectAtIndex:i];
NSError *error = nil;
NSString *text = [[NSString alloc] initWithContentsofFile:fullPath
encoding:NSUTF8StringEncoding
error:&error];
if (text == nil)
NSLog(#"%#", error);
else
NSLog(#"%#", text);
The above will only work if the files actually are encoded using UTF-8. If you are unsure of the encoding, you can let the framework try and figure it out for you with:
NSString *fullPath = [folderLabel.stringValue stringByAppendingPathComponent:[onlyMs objectAtIndex:i];
NSError *error = nil;
NSStringEncoding enc;
NSString *text = [[NSString alloc] initWithContentsofFile:fullPath
usedEncoding:&enc
error:&error];
if (text == nil)
NSLog(#"%#", error);
else
NSLog(#"%#", text);