I want to let user to choose a directory for saving a file. but how to make sure the url is a directory not a file?
NSOpenPanel* panel = [NSOpenPanel openPanel];
[panel setCanChooseDirectories:YES];
[panel setCanCreateDirectories:YES];
[panel beginSheetModalForWindow:self.window completionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
NSArray* urls = [panel URLs];
for (NSURL *url in urls) {
//here how to judge the url is a directory or a file
}
}
}];
Update for anyone reading this in the future:
In Swift, checking if the picked path is a file can be avoided by using
panel.canChooseFiles = false
// First, check if the URL is a file URL, as opposed to a web address, etc.
if (url.isFileURL) {
BOOL isDir = NO;
// Verify that the file exists
// and is indeed a directory (isDirectory is an out parameter)
if ([[NSFileManager defaultManager] fileExistsAtPath: url.path isDirectory: &isDir]
&& isDir) {
// Here you can be certain the url exists and is a directory
}
}
Swift 4 version:
if (url.isFileURL) {
var isDir: ObjCBool = false
if (FileManager.default.fileExists(atPath: url.path, isDirectory: &isDir)) {
if isDir.boolValue {
print("It's a Directory path")
} else {
print("It's a file path")
}
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With