How to show window with "Select file" in objective-C cocoa - objective-c

I've got some action in my application on OS X where I have to select file from finder. I want to display window like: "Open file". I know that this let me open url with path:
[[NSWorkspace sharedWorkspace] openURL:[NSURL fileURLWithPath:NSHomeDirectory() isDirectory:YES]];
But how to show window with "Select" button. This window should let me to get info about selected file.
How can I do this correctly?
Thank you for help.

The code for previous answers :
NSOpenPanel *op = [NSOpenPanel openPanel];
op.canChooseFiles = YES;
op.canChooseDirectories = YES;
[op runModal];
self.txtFilePath.stringValue = [op.URLs firstObject];
in op.URLs you can find paths for all files you just selected.

Building on EderYif's answer, the following doesn't produce a compiler warning and also removes the 'file://' part of the returned filename.
NSOpenPanel *op = [NSOpenPanel openPanel];
[op setCanChooseFiles:true];
[op setCanChooseDirectories:true];
[op runModal];
NSString* file = [[op.URLs firstObject] absoluteString];
NSString* fixedFile = [file stringByReplacingOccurrencesOfString:#"file://"
withString:#""];
[[self textFilePath] setStringValue:fixedFile];

#Perception and #omz gives me good answer. Answer is NSOpenPanel.

Related

How to acquire a file path using objective c

I want a function which just returns the full file path of a file selected in finder.
I am currently have this function:
+ (NSString*)choosePathWindow:(NSString*)title buttonTitle:(NSString*)buttonTitle allowDir:(BOOL)dir allowFile:(BOOL)file{
[NSApp activateIgnoringOtherApps:YES];
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel setLevel:NSFloatingWindowLevel];
[openPanel setAllowsMultipleSelection:NO];
[openPanel setCanChooseDirectories:dir];
[openPanel setCanCreateDirectories:dir];
[openPanel setCanChooseFiles:file];
[openPanel setMessage:title];
[openPanel setPrompt:buttonTitle];
NSString* fileName = nil;
if ([openPanel runModal] == NSModalResponseOK)
{
for( NSURL* URL in [openPanel URLs])
{
fileName = [URL path];
}
}
[openPanel close];
return fileName;
}
But this usually behaves awfully and stutters into view and often hangs after choosing a file (I have an i7-7700k and 16GB ddr4) and always hangs when clicking cancel. I also believe that this may be to do with external network mounts I have. But any other software such as PHPStorm or Chrome work fine with the same window.
Is there a better way to do this?
The code looks fine. Try calling your function from main thread; modal dialogs need this and usually don't enforce it themselves. In any case the Powebox (the thing that runs NSOpenPanel in sandbox) is a bit of a beast. Also you might get different results with debug build launched directly from Xcode (not so good) and release build launched from Finder.
To test NSOpenPanel: Try running your App under a guest account to eliminate all stuff that's cluttering the sandbox .
My code:
(actually in production:)
-(void)OpenIt {
NSOpenPanel* panel = [NSOpenPanel openPanel];
// This method displays the panel and returns immediately.
// The completion handler is called when the user selects an
// item or cancels the panel.
[panel setTitle: "title...."];
NSString *title = NSLocalizedString(#"CHOOSE_FILE", #"");
[panel setMessage: title];
[panel beginWithCompletionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
NSURL* theDoc = [[panel URLs] objectAtIndex:0];
NSLog(#"%#", theDoc);
// Open the document using url
[self openUsingURL: theDoc];
}
}];
}

Objective C how to print and NSArray of strings into an NScrollView and NSTextField

I am making a simple gui on Xcode. I use a button to load a text file into an NSArray like below.
NSOpenPanel *panel = [NSOpenPanel openPanel];
if ([panel runModal] == NSFileHandlingPanelOKButton) {
albumURL = [panel URL];
info = [NSString stringWithContentsOfURL: albumURL encoding: NSASCIIStringEncoding error: NULL];
listItems = [info componentsSeparatedByString:#"\n"];
NSString *combinedString = [listItems componentsJoinedByString:#"\n"];
//[self.TrackList setValue:combinedString forKey: combinedString];
}
I want to print the contents of the array into the NSscrollview as a series of strings. I also want to print the context of some specific index into different textfields.
So far I only managed to figure out how to put a set string into the textfield like below.
[self.myTextField setStringValue:#"My string of whatever"];
I'm new to this stuff so if you need more info please ask.

Get file type description by extension

How can I get the description of the file type like it does in Finder.app by using only file extension? In other words I want to get that field in NSString:
Here's a little something quick 'n' dirty that illustrates what you need:
NSOpenPanel *openPanel = [[NSOpenPanel alloc] init];
[openPanel runModal];
NSString *path = [[openPanel URL] path];
NSString *type = [[NSWorkspace sharedWorkspace] typeOfFile:path error:NULL];
NSLog(#"%#", [[NSWorkspace sharedWorkspace] localizedDescriptionForType:type]);
The open panel lets you choose a file. NSWorkspace provides for first determining the UTI of the file (given its path), and then using the UTI to get the localized string describing the file type.
EDIT:
If you positively have got to use only the file extension, then use these three lines instead of the last three above:
NSString *extension = [[[openPanel URL] path] pathExtension];
CFStringRef uti = UTTypeCreatePreferredIdentifierForTag(kUTTagClassFilenameExtension, (__bridge CFStringRef) extension, NULL);
NSLog(#"%#", [[NSWorkspace sharedWorkspace] localizedDescriptionForType:(__bridge NSString *) uti]);
You should get that by supplying the files universal type identifier to localizedDescriptionForType: of NSWorkspace.

Use NSOpenpanel and NSfilemanager to find contents of directory

I'm new to objective-c so please excuse my lack of knowledge. I have a snippet of code here that I can't seem to get working properly. What I'd like to do is present a directory selection panel upon a button click. Once the user selects a directory I'd like to make an array of everything in the directory. Eventually I want to use this array to have a list of sub-directories and files (everything in the directory the user selects) to be copied to another location.
I have a warning that says Instance method '-contentsofdirectoryaturl:options:error' not found (return type defaults to id). I'm not exactly sure what that means or how to fix it and I suspect that this is my problem. Any advice provided would be great. Thanks!
- (IBAction)selectfiles:(id)sender {
NSOpenPanel *openPanel = [NSOpenPanel openPanel];
[openPanel setCanChooseDirectories:YES];
[openPanel setCanChooseFiles:NO];
[openPanel setAllowsMultipleSelection:NO];
if ( [openPanel runModal] == NSOKButton ) {
NSArray *accountPath = [openPanel URLs];
NSLog (#"%#", accountPath);
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSArray *contents;
contents = [filemgr contentsOfDirectoryAtURL:accountPath options:(NSDirectoryEnumerationSkipsHiddenFiles) error:nil];
}
}
contentsOfDirectoryAtURL: has an additional argument includingPropertiesForKeys: which you have omitted. That is why the compiler warns you. That argument is a list of properties you want to be prefetched. In the simplest case, you can specify an empty array.
Another error is that [openPanel URLs] returns an array of URLs, even if only one item is selected.
So your code should look like this:
NSURL *accountPath = [[openPanel URLs] objectAtIndex:0];
NSLog (#"%#", accountPath);
NSFileManager *filemgr;
filemgr = [NSFileManager defaultManager];
NSArray *contents;
contents = [filemgr contentsOfDirectoryAtURL:accountPath
includingPropertiesForKeys:[NSArray array]
options:(NSDirectoryEnumerationSkipsHiddenFiles)
error:nil];

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