I have a File Open Dialog box in my application to select files from, but when the user clicks the 'Select' button in the box, it obviously won't do anything. How do I extract the filepath from the selected file? I need the filepath so I can get the contents of the file to encrypt. Initially, I hard coded the file I would use into my application, but that was only for testing purposes. Here is what I am using for the File Open Dialog Box:
int i;
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setCanChooseDirectories:YES];
[openDlg setPrompt:#"Select"];
NSString *fileName = [pathAsNSString lastPathComponent];
[fileName stringByDeletingPathExtension];
if ([openDlg runModalForDirectory:nil file:nil] == NSOKButton )
{
NSArray* files = [openDlg filenames];
for( i = 0; i < [files count]; i++ )
{
[files objectAtIndex:i];
}
}
Thanks so much for the help.
Use - (NSArray *)URLs method instead of filenames.
Your code is already handling the files that the user has selected, you're just not doing anything with them.
The array returned from the ‑filenames method contains the paths to the files that the user selected as NSString objects. If they have only selected one file, there will only be one object in the array. If they have selected no files, the array will be empty.
if ([openDlg runModalForDirectory:nil file:nil] == NSOKButton )
{
NSArray* files = [openDlg filenames];
for(NSString* filePath in [openDlg filenames])
{
NSLog(#"%#",filePath);
//do something with the file at filePath
}
}
If you only want the user to be able to select a single file, then call [openPanel setAllowsMultipleSelection:NO] when you're configuring the panel. That way, there will be a maximum of one entry in the filenames array.
As #VenoMKO points out, the ‑filenames method is now deprecated and you should use the ‑URLs method instead. This will return an array of file NSURL objects rather than an array of NSStrings. Since pretty much all the file handling APIs in Snow Leopard were revised to take URLs, this would be the preferred option.
You Want to Get File Path Using Following Code
NSOpenPanel* openPanel = [NSOpenPanel openPanel];
[openPanel setCanChooseFiles:YES];
[openPanel setCanChooseDirectories:NO];
[openPanel setAllowsMultipleSelection: NO];
[openPanel setAllowedFileTypes:ArrExtension ];
if ([openPanel runModal] == NSOKButton ){
NSString *FilePath = [NSString stringWithFormat:#"%#",[openPanel URL]];
[openPanel canHide];
}
Related
Im trying to save the file into the path, which I manual input into text field or select from FileBrowser. However it doesn't work.
If I drop path to textfield then it working fine. Could you help me.
- (IBAction)btnRawDataPath:(id)sender {
_txtLog.stringValue = #"";
// Create the File Open Dialog class.
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
// Enable the selection of files in the dialog.
[openDlg setCanChooseFiles:NO];
// Multiple files not allowed
[openDlg setAllowsMultipleSelection:NO];
// Can't select a directory
[openDlg setCanChooseDirectories:YES];
// Display the dialog. If the OK button was pressed,
// process the files.
if ( [openDlg runModal] == NSModalResponseOK )
{
// Get an array containing the full filenames of all
// files and directories selected.
NSArray* urls = [openDlg filenames];
// Loop through all the files and process them.
for(int i = 0; i < [urls count]; i++ )
{
//fileList.push_back(std::string([[[urls objectAtIndex:i] path] UTF8String]));
NSString* url = [urls objectAtIndex:i] ;
NSLog(#"Url: %#", url);
_txtRawDataPath.stringValue = url;
}
}
}
// EXCUTE
NSString *filePath = [_txtRawDataPath.stringValue stringByAppendingPathComponent:#"outputFIle.csv"];
NSData* settingsData;
settingsData = [mainString dataUsingEncoding: NSASCIIStringEncoding];
if ([settingsData writeToFile:filePath atomically:YES ])
NSLog(#"%#", filePath);
OSX Project:
Something strange is happening, hoping someone has a thought on the solution. I have a coredata project and I'm working on the backup/restore portion.
Initially I had hardcoded the file name and used the Applications file directory for the storage location - this all worked without an issue.
Next, I used NSOpenPanel to select the storage location. In this step, I used the same filename in the restore process - this worked without issue.
Last, I used NSOpenPanel to select the file to restore - this is the issue. I receive errors and the file is NOT opened.
Create backup method
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:NO];
[openDlg setCanChooseDirectories:YES];
[openDlg setAllowsMultipleSelection:NO];
NSArray *pathName;
if ( [openDlg runModal] == NSOKButton )
{
pathName = [openDlg URLs];
}
filePathNameBackup = [pathName objectAtIndex:0];
NSDateFormatter *format = [[NSDateFormatter alloc]init];
[format setDateFormat:#"yyyyMMddHHmmssSSS"];
NSString *stringOfDate = [format stringFromDate:[NSDate date]];
fileNameBackup = [fileNameBackup stringByAppendingString:stringOfDate];//fileNameBackup is defined earlier as "datafile"
fileNameBackup = [fileNameBackup stringByAppendingString:#".backup"];
//Created a filename with a timestamp
filePathNameBackup = [filePathNameBackup URLByAppendingPathComponent:fileNameBackup];
NSURL *urlbackup = filePathNameBackup;
...then the rest of the code to save the file - which does work
Then in the restore method I have the following:
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setCanChooseDirectories:NO];
[openDlg setAllowsMultipleSelection:NO];
[openDlg setAllowedFileTypes:[NSArray arrayWithObject:#"backup"]];
NSArray *pathName;
if ( [openDlg runModal] == NSOKButton )
{
pathName = [openDlg URLs];
NSURL *urlbackup = [pathname objectAtIndex:0];
... Then the rest of the restore method
The above does NOT work, I receive an error when creating the store - states it can not open file.
NSPersistentStore *restoreStore = [migrationCoordinator addPersistentStoreWithType:NSSQLiteStoreType configuration:nil URL:urlbackup options:nil error:nil];
Now the funny crazy part is if I use the file path name from the create backup method, it will work (filePathNameBackup):
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setCanChooseDirectories:NO];
[openDlg setAllowsMultipleSelection:NO];
[openDlg setAllowedFileTypes:[NSArray arrayWithObject:#"backup"]];
NSArray *pathName;
if ( [openDlg runModal] == NSOKButton )
{
pathName = [openDlg URLs];
NSURL *urlbackup = filePathNameBackup;
... Then the rest of the restore method
The above will work. I open the App, create a backup (Selecting the location in NSOpenPanel during the create backup method), change the file, save it, restore the backup, everything works!!
So why won't this work using NSOpenPanel to select the backup file?
If I NSLog the URL's, they both appear to be identical.
Summary of restore method:
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setCanChooseDirectories:NO];
[openDlg setAllowsMultipleSelection:NO];
[openDlg setAllowedFileTypes:[NSArray arrayWithObject:#"backup"]];
NSArray *pathName;
if ( [openDlg runModal] == NSOKButton )
{
pathName = [openDlg URLs];
NSURL *urlbackup = filePathNameBackup; //THIS WORKS (Use filename created during backup)
NSURL *urlbackup = [pathname objectAtIndex:0]; //THIS DOESNOT WORK
NO THEY BOTH ARE NOT BEING USED TOGETHER - I rem out one or the other urlbackup definitions before I run the program.
Again, why wont NSURL *urlbackup = [pathname objectAtIndex:0]; work?
Any thoughts would be appreciate, I was up late last night (this morning) and about ready to throw something. It just does not make any sense.
---[EDIT-----
The error received is error:14, unable to open database file
---[EDIT #2]----
Performed several more tests and I believe it has to do with sandboxing - as I00phole pointed out, just not sure how yet. If I hardcode a filename and use the app directory, all is good. If I hardcode another directory, it will not work.
I am not extremely familiar with sandboxing - any suggestions would be appreciated.
I already refered this link
iMedia
Now i am using NSOpenPanel to open iPhoto library folder.
Here is the code which allow to open.
int i = 0;
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setCanChooseFiles:YES];
[openDlg setAllowedFileTypes:[NSArray arrayWithObjects:#"public.image",#"public.video",nil]];
[openDlg setAllowsMultipleSelection:TRUE];
[openDlg setAllowsOtherFileTypes:NO];
if ( [openDlg runModal] == NSOKButton )
{
NSArray *files = [openDlg URLs];
for( i = 0; i < [files count]; i++ )
{
NSLog(#"File path: %#", [[files objectAtIndex:i] path]);
}
}
This code always open my Finder library folder, As i want to open Media Photo and Movies folder directly.
Please give me any solution.
I have attached here one screen shot.
Thanks & Regards,
You may consider adding the following code snipet:
NSFileManager *fileManager = [NSFileManager defaultManager];
NSError *error = nil;
NSURL *picturesURL = [fileManager URLForDirectory:NSPicturesDirectory inDomain:NSUserDomainMask appropriateForURL:NULL create:NO error:&error];
NSURL *iPhotoURL = [picturesURL URLByAppendingPathComponent:#"iPhoto Library.photolibrary"];
[openDlg setDirectoryURL:iPhotoURL];
// Now run the dialog
This won't help if the user has moved his iPhoto library to some non-standard location.
There is a private API of Apple that contains exactly the control you want to access;
this control is an ILMediaBrowserView and provides the exact same view than the one in NSOpenDialog. If you are planning an AppStore release of your app don't use it but it can be useful. The framework to integrate to your project to get that view is iLifeMediaBrowser.framework in /System/Library/PrivateFrameworks.
I am new to cocoa programming, Using the below code I want to show the selected file names in window. How can I do that?
- (IBAction)selectFile:(id)sender {
int i; // Loop counter.
// Create the File Open Dialog class.
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
NSArray *fileTypes = [NSArray arrayWithObjects:#"wmv", #"3gp", #"mp4", #"avi", #"mp3", #"mma", #"wav", nil];
// Enable the selection of files in the dialog.
[openDlg setCanChooseFiles:YES];
//Enable multiple selection of files
[openDlg setAllowsMultipleSelection:YES];
// Enable the selection of directories in the dialog.
[openDlg setCanChooseDirectories:YES];
// Display the dialog. If the OK button was pressed,
// process the files.
if ( [openDlg runModalForDirectory:nil file:nil types:fileTypes] == NSOKButton )
{
// Get an array containing the full filenames of all
// files and directories selected.
NSArray* files = [openDlg filenames];
// Loop through all the files and process them.
for( i = 0; i < [files count]; i++ )
{
NSString* fileName = [files objectAtIndex:i];
NSLog(#"filename::: %#", fileName);
// Do something with the filename.
}
}
}
In NSLog I am getting the names, what I want is to show the names on window too, to show the user that these files are selected.
Which view can be used? What is the way to achieve this?
Thanx
Use an NSTextView or an NSTextField.
NSArray* files = [openDlg filenames];
NSString* fileName;
// Loop through all the files and process them.
for( i = 0; i < [files count]; i++ )
{
fileName =[fileName stringByAppendingString:[files objectAtIndex:i];
// Do something with the filename.
}
NSLog(#"filename::: %#", fileName);
textView.text=fileName;
runModalForDirectory:file:types: is deprecated in OS X v10.6. You could use runModal instead.
You can set path using setDirectoryURL:, and you can set fileTypes using setAllowedFileTypes:.
I'm learning Objective-C and trying to develop a simple zipper application, but I stopped when now, when I need to insert a button at my dialog and this button opens a Open File Dialog that will select a file to compress, but I never used a Open File Dialog, then how I can open it and store the user selected file in a char*? Thanks.
Remember that I'm using GNUstep(Linux).
Thanks #Vlad the Impala I am updating your answers for people who use OS X v10.6+
// Create the File Open Dialog class.
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
// Enable the selection of files in the dialog.
[openDlg setCanChooseFiles:YES];
// Multiple files not allowed
[openDlg setAllowsMultipleSelection:NO];
// Can't select a directory
[openDlg setCanChooseDirectories:NO];
// Display the dialog. If the OK button was pressed,
// process the files.
if ( [openDlg runModal] == NSOKButton )
{
// Get an array containing the full filenames of all
// files and directories selected.
NSArray* urls = [openDlg URLs];
// Loop through all the files and process them.
for(int i = 0; i < [urls count]; i++ )
{
NSString* url = [urls objectAtIndex:i];
NSLog(#"Url: %#", url);
}
}
In case someone else needs this answer, here it is:
int i;
// Create the File Open Dialog class.
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
// Enable the selection of files in the dialog.
[openDlg setCanChooseFiles:YES];
// Multiple files not allowed
[openDlg setAllowsMultipleSelection:NO];
// Can't select a directory
[openDlg setCanChooseDirectories:NO];
// Display the dialog. If the OK button was pressed,
// process the files.
if ( [openDlg runModalForDirectory:nil file:nil] == NSOKButton )
{
// Get an array containing the full filenames of all
// files and directories selected.
NSArray* files = [openDlg filenames];
// Loop through all the files and process them.
for( i = 0; i < [files count]; i++ )
{
NSString* fileName = [files objectAtIndex:i];
}
For people who use OS X v10.10+, replace in Far Jangtrakool answer:
if ( [openDlg runModal] == NSOKButton )
by
if ( [openDlg runModal] == NSModalResponseOK )