I am selecting files through this code:
- (IBAction)selectFile:(id)sender {
// Create the File Open Dialog class.
NSOpenPanel* openDlg = [NSOpenPanel openPanel];
[openDlg setPrompt:#"Select"];
fileTypes = [NSArray arrayWithObjects:#"wmv", #"3gp", #"mp4", #"avi", #"mp3", #"mma", #"wav", #"jpeg", #"png", #"jpg", #"tiff", nil];
// NSArray *JpegfileTypes = [NSArray arrayWithObjects:#"jpeg", #"png", #"jpg", #"tiff", #"mp3" 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.
files = [[openDlg filenames] retain];
int i; // Loop counter.
// Loop through all the files and process them.
for( i = 0; i < [files count]; i++ )
{
NSString *tempFilePath = [files objectAtIndex:i];
NSLog(#"tempFilePath::: %#",tempFilePath);
inputFilePath = [[files objectAtIndex:i] retain];
NSLog(#"filename::: %#", inputFilePath);
// Do something with the filename.
[selectedFile setStringValue:inputFilePath];
NSLog(#"selectedFile:::: %#", selectedFile);
}
}
}
Then after selection I have used this code to process the selected file.
- (IBAction)setMessage:(id)sender {
[fileGenProgress startAnimation:self];
NSString *message = [[NSString alloc] initWithFormat:#"Started"];
[lblMessage setStringValue:message];
[message release];
[self startProcessingVideoFile];
[self startProcessingAudioFile];
[self startProcessingJpg];
}
The issue I am facing is that, I am not getting that how would I compare the different strings like if the selected file was 3gp/mp4 or jpg or mp3. As if user has selected some video file then the method [self startProcessingVideoFile]; will run and if he has selected some JPG or PNG etc file then [self startProcessingAudioFile]; method will run.
As selected will be having a path not only the extension of the file. So in this scenario how can I force the - (IBAction)setMessage:(id)sender method to run the appropriate method.
You can get string's extension (format) like this:
NSString *extension = [stringPath pathExtension];
And for comparing now it's very easy when You know what extension Your file is. For example:
NSLog(extension);
if ([extension isEqualToString:#"3gp"] || [ext isEqualToString:#"mp4"]) {
[self startProcessingVideoFile];
}
and etc.
Update:
Your IBAction:SetMessage should look like this:
- (IBAction)setMessage:(id)sender {
[fileGenProgress startAnimation:self];
NSString *message = [[NSString alloc] initWithFormat:#"Started"];
[lblMessage setStringValue:message];
[message release];
NSString *extension = [inputFilePath pathExtension];
NSLog(extension);
if ([extension isEqualToString:#"3gp"] || [ext isEqualToString:#"mp4"]) {
[self startProcessingVideoFile];
}
// And etc for others formats.
//[self startProcessingAudioFile];
//[self startProcessingJpg];
}
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);
This method found in the AppDelagate, loads a text file of my choosing and splits the context of the text file into an array.
Im having trouble displaying the contents of the array in my NSScrollview * called self.textView.
I am not sure how to update the text view with each member of the array.
- (IBAction)loadButton:(id)sender {
NSOpenPanel *panel = [NSOpenPanel openPanel];
if ([panel runModal] == NSFileHandlingPanelOKButton) {
NSURL *bookUrl = [panel URL];
NSString *contents = [NSString stringWithContentsOfURL: bookUrl encoding: NSASCIIStringEncoding error: NULL];
NSArray *loadedBook = [contents componentsSeparatedByString:#"#NP#"];
self.textView.value = loadedBook[0];
}
}
The right method is setString:, which is declared in NSText.
your code should be:
- (IBAction)loadButton:(id)sender {
NSOpenPanel *panel = [NSOpenPanel openPanel];
if ([panel runModal] == NSFileHandlingPanelOKButton) {
NSURL *bookUrl = [panel URL];
NSString *contents = [NSString stringWithContentsOfURL: bookUrl encoding: NSASCIIStringEncoding error: NULL];
NSArray *loadedBooks = [contents componentsSeparatedByString:#"#NP#"];
[self.textView setString:bookStr];
}
}
UPDATE
Take a look at this question, to see how to add text to a NSScrollView
I've implemented a simple application that basically outputs informations about a given triangle (see image). I've created the triangles programmatically. I would like to improve this example providing a mechanism to open a say .tri file with its sides (e.g. 3 4 5). How can I achieve that ? I've done some research and found out there's a method called openDocument.. How would I use this on my application ? Can someone give me an example of how to achieve that ? Apparently it's not a document-based application.. I've got this code on github: https://github.com/mcand/TableViewMacExample.
I managed to make the panel appear like below.
- (IBAction)openDocument:(id)sender{
NSOpenPanel* openPanel = [NSOpenPanel openPanel];
[openPanel setAllowedFileTypes:[NSArray arrayWithObjects:#"tri", #"qua",nil]];
[openPanel runModal];
}
After opening the file, I cannot change the values of my NSTableView. The code is like that:
- (IBAction)openDocument:(id)sender{
NSOpenPanel* panel = [NSOpenPanel openPanel];
[panel setAllowedFileTypes:[NSArray arrayWithObjects:#"tri", #"qua",nil]];
[panel beginWithCompletionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
NSURL* file = [[panel URLs] objectAtIndex:0];
[self performSelectorInBackground:#selector(triangle:) withObject:file];
}
}];
}
-(void) triangle:(NSURL *)file{
NSError *error;
NSString *words = [[NSString alloc] initWithContentsOfURL:file encoding:NSUTF8StringEncoding error:&error];
NSLog(#"%#", words);
NSArray* lines = [words componentsSeparatedByCharactersInSet:[NSCharacterSet newlineCharacterSet]];
NSMutableArray *shapes = [[NSMutableArray alloc] init];
while (lines) {
NSArray*info = [words componentsSeparatedByString:#";"];
// Creates triangles to be populated
CGFloat side1 = (CGFloat)[info[0] floatValue];
CGFloat side2 = (CGFloat)[info[1] floatValue];
CGFloat side3 = (CGFloat)[info[2] floatValue];
Triangle *triangle = [[Triangle alloc] initWithSides:side1 side:side2 andSide:side3];
[shapes addObject:triangle];
}
self.formsArray = shapes;
[self performSelectorOnMainThread:#selector(updateTableView) withObject:nil waitUntilDone:YES];
}
-(void)updateTableView{
[self.tableView reloadData];
}
#end
I have NSSavePanel with accessoryView to let the user select a graphic format so that they can save an image (NSImage) as a file. So far, I have the following. (I'm skipping some lines to make it short.)
- (void)exportFile {
NSString *filename;
if (formatIndex1 == 0) { // Default selection by user in Preferences
filename = #"Untitled.bmp";
}
else if (formatIndex1 == 1) {
filename = #"Untitled.gif";
}
...
[panel setAllowedFileTypes:[[NSArray alloc] initWithObjects:#"bmp",#"gif",#"jpg",#"jp2",#"png",nil]];
[panel setAllowsOtherFileTypes:NO];
[panel setExtensionHidden:NO];
[panel setCanCreateDirectories:YES];
[panel setNameFieldStringValue:filename];
[panel setAccessoryView:accessoryView1];
[formatMenu1 setAction:#selector(dropMenuChange:)]; // formatMenu1 is NSPopUpButton
[formatMenu1 setTarget:self];
[panel beginSheetModalForWindow:window completionHandler:^(NSInteger result) {
if (result == NSFileHandlingPanelOKButton) {
// getting panel url
}
}];
}
-(void)dropMenuChange:(NSPopUpButton *)sender {
NSSavePanel *savePanel = (NSSavePanel *)[sender window];
[savePanel setNameFieldStringValue:#"..."];
}
I'm not 100% sure that I'm doing it right. What I want to achieve is that I want to append the right extension to the current file name whenever the user selects a file format on accessoryView's NSPopUpButton. Is there a magical way of doing that? Or do I have to set the current file name with the right extension to setNameFieldStringValue programmatically for myself?
Thank you for your help.
What I want to achieve is that I want to append the right extension to the current file name whenever the user selects a file format on accessoryView's NSPopUpButton. Is there a magical way of doing that?
Yes, there is. You need not do it yourself with setNameFieldStringValue: , let the savePanel do it. Let us assume fileName is a full path like /Users/hg/Pictures/2013/08/Airplanes/pic123.png and it exists an accessoryView for the savePanel with a matrix of radio buttons. Each button has a title like #"jpg" or #"png" or... The action of the matrix is -selectFileType:
- (IBAction) selectFileType:(id)sender
{
[savePanel setAllowedFileTypes:#[ [[sender selectedCell] title] ] ];
// this will set the right extension
}
For using the savePanel I tried the following code:
- (void) saveImage:(NSImage *) theImg
{
savePanel = [NSSavePanel savePanel];
NSString *imageName = [fileName lastPathComponent];
NSString *suffix = [imageName pathExtension];
NSString *baseName = [imageName stringByDeletingPathExtension];
// prepare the savePanel
[savePanel setAccessoryView:accessoryView];
[savePanel setAllowedFileTypes:#[ suffix ] ];
[savePanel setDirectoryURL:[NSURL fileURLWithPath:fileName]]; // convert to URL
[savePanel setNameFieldStringValue:baseName ]; // without extension !
// savePanel does append the suffix
// and now start the savePanel and choose the wanted fileType
int rtn = [savePanel runModal]; // preferred method since 10.6
if( rtn==NSFileHandlingPanelCancelButton) return; // do nothing
// finally create and save the file
if( [[[savePanel allowedFileTypes] objectAtIndex:0] isEqualToString:#"jpg" ){
// save as jpg-file
}
// check for other fileTypes
. . .
}
You have to set current file name with the right extension using setNameFieldStringValue
-(void)dropMenuChange:(NSPopUpButton *)sender {
NSSavePanel *savePanel = (NSSavePanel *)[sender window];
NSString *nameFieldString = [savePanel nameFieldStringValue];
NSString *nameFieldStringWithExt = [NSString stringWithFormat:#"%#.%#",[savePanel nameFieldStringValue], popupvalue];
[savePanel setNameFieldStringValue:nameFieldStringWithExt];
}
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:.