Add item from finder - objective-c

I have a table with the classic + - buttons underneath it. (on mac)
I want to press the + button, and open a little finder to select a file, to add it on the table.
How can I do that?
I searched the developer reference, but didn't find it..

Use NSOpenPanel.
For a guide on dealing with files and using open panels, see the Application File Management guide.
For instance:
- (IBAction)addFile:(id)sender
{
NSInteger result;
NSArray *fileTypes = [NSArray arrayWithObject:#"html"];
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setAllowsMultipleSelection:YES];
[oPanel setDirectory:NSHomeDirectory()];
[oPanel setCanChooseDirectories:NO];
result = [oPanel runModal];
if (result == NSFileHandlingPanelOKButton) {
for (NSURL *fileURL in [oPanel URLs]) {
// do something with fileURL
}
}
}
Another example using a sheet:
- (IBAction)addFile:(id)sender
{
NSArray *fileTypes = [NSArray arrayWithObject:#"html"];
NSOpenPanel *oPanel = [NSOpenPanel openPanel];
[oPanel setAllowsMultipleSelection:YES];
[oPanel setDirectory:NSHomeDirectory()];
[oPanel setCanChooseDirectories:NO];
[oPanel beginSheetModalForWindow:[self window]
completionHandler:^(NSInteger result) {
if (result == NSFileHandlingPanelOKButton) {
for (NSURL *fileURL in [oPanel URLs]) {
// do something with fileURL
}
}
}];
}

Related

NSOpenPanel on Main-Thread doesn't work

I tried to use NSOpenPanel for my program and it doesn't work at all, because the NSOpenpanel doesn't run on the main thread.
Here's my code
NSString *strURL;
NSOpenPanel *fileContents;
NSURL *panelURL;
NSArray *fileTypes = [NSArray arrayWithObjects:#"strings", #"STRINGS", nil];
fileContents = [NSOpenPanel openPanel];
[fileContents setCanChooseDirectories:NO];
[fileContents setCanChooseFiles:YES];
[fileContents setAllowedFileTypes:fileTypes];
[fileContents setAllowsMultipleSelection:NO];
NSInteger openPanelButton = [fileContents runModal];
if(openPanelButton == NSModalResponseOK)
{
panelURL = [fileContents URL];
strURL = panelURL.absoluteString;
}
NSArray *linesReadOnly = [strURL componentsSeparatedByString:#"\n"];
I tried both of the following codes:
[fileContents performSelectorOnMainThread:#selector(runModal) withObject:nil waitUntilDone:YES];
and
dispatch_sync(dispatch_get_main_queue(), ^{
//do UI stuff
});
It just doesn't work at all to get this on the main-thread. What do I do wrong?
You can check the below code.
//Open pannel to select any file or image and send it to server with upload file API
let openPannel: NSOpenPanel = NSOpenPanel()
openPannel.allowsMultipleSelection = true
openPannel.canChooseFiles = true
openPannel.canChooseDirectories = false
openPannel.runModal()
let choosenFile = openPannel.URL
if choosenFile != nil
{
let uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension,(choosenFile?.pathExtension!)!,
nil)
if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeImage) {
print("This is an image!")
}
else if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeFolder) {
print("This is a folder!")
}
else if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeAliasFile) {
print("This is a zip!")
}
else if UTTypeConformsTo((uti?.takeRetainedValue())!, kUTTypeSpreadsheet) {
print("This is a sheet!")
}
}

Displaying text in text view from NSArray

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

Open a document with Objective-C for an OS X application

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

Calling methods after comparing string objects from NSArray Cocoa

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];
}

Using Cocoa to create an icon for a folder

In my Mac OS application, I'm prompting a user to create a new folder. I would like to apply an icon to this folder using Cocoa when it is created. Currently, to create the folder, I'm using the following code:
- (IBAction)browseFiles:(id)sender
{
NSOpenPanel *oPanel = [[NSOpenPanel openPanel] retain];
[oPanel setCanChooseDirectories:YES];
[oPanel setCanChooseFiles:NO];
[oPanel setDelegate:self];
[oPanel setCanCreateDirectories:YES];
[oPanel beginSheetForDirectory:NSHomeDirectory()
file:nil
types:nil
modalForWindow:nil
modalDelegate:self
didEndSelector:#selector(filePanelDidEnd:
returnCode:
contextInfo:)
contextInfo:nil];
}
After choosing a directory, the user clicks a confirm button that calls a function with the following method:
bool set = [[NSWorkspace sharedWorkspace] setIcon:[NSImage imageNamed:#"icon.icns"] forFile:path options:NSExcludeQuickDrawElementsIconCreationOption];
While the piece of code above does return "YES", the icon is not successfully applied to the folder. Am I doing something wrong in my code?
Thanks.
The NSWorkspace method works like a charm here. Maybe your icon is in an invalid format?
I tried setIcon: using the Finder icon:
- (IBAction)setFolderIcon:(id)sender
{
NSOpenPanel* openPanel = [NSOpenPanel openPanel];
[openPanel setCanChooseFiles:NO];
[openPanel setCanChooseDirectories:YES];
switch([openPanel runModal])
{
case NSFileHandlingPanelOKButton:
{
NSURL* directoryURL = [openPanel directoryURL];
NSImage* iconImage = [[NSImage alloc] initWithContentsOfFile:#"/System/Library/CoreServices/Finder.app/Contents/Resources/Finder.icns"];
BOOL didSetIcon = [[NSWorkspace sharedWorkspace] setIcon:iconImage forFile:[directoryURL path] options:0];
NSLog(#"%d", didSetIcon);
[iconImage release];
}
case NSFileHandlingPanelCancelButton:
{
return;
}
}
}