Answer the question
In order to leave comments, you need to log in
How to get a list of files in an os x directory?
I am developing an application in objective c. The user selects a directory (using NSOpenPanel) and then the application displays a list of files in this directory. There are no problems in this. However, if you open the application again and do not select a directory through NSOpenPanel, but immediately want to get a list of files in the directory selected in the previous launch, then an NSCocoaErrorDomain Code=257 error occurs.
I suspect that if the user selects a directory manually through NSOpenPanel, then the system somehow remembers this and gives access to read this directory and get its files (I use the contentsOfDirectoryAtPath method), and if the user does not select a directory through NSOpenPanel and tries to get a list of its files , an access error is generated. How to be in this case?
Answer the question
In order to leave comments, you need to log in
@Cassar : Simplified like this:
If an NSOpenPanel call is made
NSOpenPanel *panel = [[NSOpenPanel alloc] init];
[panel setCanChooseDirectories:YES];
[panel setCanChooseFiles:NO];
[panel setAllowsMultipleSelection:NO];
if([panel runModal] == NSOKButton){
...
}
NSArray *urls = [panel URLs];
NSArray *dirs = [[NSFileManager defaultManager] contentsOfDirectoryAtPath: [urls[0] path] error:&err];
@This_man
First, it [panel URLs]
returns an array of NSURLs, and to use them in contentsOfDirectoryAtPath: you need to convert to NSString using absoluteString or path like you have.
Secondly, the code of the form
NSError *error = nil;
NSArray *arr = [[NSFileManager defaultManager] contentsOfDirectoryAtPath:@"//" error:&error];
NSLog(@"%@", arr);
- (NSString *)resolvePath:(NSString *)path {
NSString *expandedPath = [[path stringByExpandingTildeInPath] stringByStandardizingPath];
const char *cpath = [expandedPath cStringUsingEncoding:NSUTF8StringEncoding];
char *resolved = NULL;
char *returnValue = realpath(cpath, resolved);
if (returnValue == NULL && resolved != NULL) {
printf("Error with path: %s\n", resolved);
// if there is an error then resolved is set with the path which caused the issue
// returning nil will prevent further action on this path
return nil;
}
return [NSString stringWithCString:returnValue encoding:NSUTF8StringEncoding];
}
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question