How to open a folder? - cocoa

After save a file I want to open the folder of saved file. How do I do that? Thank you very much!

If I understand your question, you want to open the folder into which something was saved in the Finder?
This should do the trick -- it assumes that you have a reference to the savePanel.
NSURL *fileURL = [savePanel URL];
NSURL *folderURL = [fileURL URLByDeletingLastPathComponent];
[[NSWorkspace sharedWorkspace] openURL: folderURL];
If you are starting with an NSString containing the path, then start with:
NSURL *fileURL = [NSURL fileURLWithPath: stringContainingPath];

Even better would be to not just open the folder, but have the saved file selected. NSWorkspace can do that for you:
[[NSWorkspace sharedWorkspace] activateFileViewerSelectingURLs:
#[ URLToSavedFile ]];
The argument is an array of URLs, so if you have only one file you want to reveal, you simply pass an array of one object.
If, for some reason, you're targeting a version of Mac OS X older than 10.6, you'd use the older path-based method instead:
[[NSWorkspace sharedWorkspace] selectFile:pathToSavedFile
inFileViewerRootedAtPath:#""];
(You want to pass an empty string for the second argument so that the Finder will reuse an existing Finder window for the folder, if there is one.)

I know this post is fairly old, but with 10.9 what you want to do is
NSString* folder = #"/path/to/folder"
[[NSWorkspace sharedWorkspace]openFile:folder withApplication:#"Finder"];

Related

why my absolute path for jpg file doesn't work

I have checked out a few similar questions and didn't find the answer to my question.
First part of the question is how to write relative path of file. I didn't get this work but let me move the second part at the moment. Since I couldn't get relative path work, so I tried absolute path. Here is the code I use:
NSString *path = [NSString stringWithFormat:#"/Users/my.name/Documents/TestFour/TestFour/Library/file%d.txt", i]; //where i is 1 or 2
//NSString *path = [NSString stringWithFormat:#"./TestFour/Library/file%d.txt", i]; //this relative path didn't work, although TestFour.xcodeproj and TestFour are in the same directory and TestFour has child directory Library and xxx.h and xxx.m files
NSString *spath = [path stringByStandardizingPath];
NSLog(#"file is %#", spath);
if (spath) {
NSString *myText = [NSString stringWithContentsOfFile:spath encoding:NSUTF8StringEncoding error:nil];
//continue, and I got myText ....
Now I have a jpg file, say myPic.jpg, in the same directory as above file1.txt, i.e., in the Library folder. I want to load this image into a UIImageView, here is my code, but it failed.
NSString *path = #"/Users/my.name/Documents/TestFour/TestFour/Library/myPic.jpg";
NSString *spath = [path stringByStandardizingPath];
[self._bgView setImage:[UIImage imageNamed:spath]];
However, I tried a web-based image, which BTW from another related thread, and it worked:
[self._bgView setImage:[[UIImage alloc] initWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:#"http://farm4.static.flickr.com/3092/2915896504_a88b69c9de.jpg"]]]];
So I'm confused why I could read the_same_folder_file1.txt but not load the_same_folder_myPic.jpg
And back to the first part, why my relative path didn't work? Not sure if this is related, I was asked and selected the default setting (Group or something like this) when I drag this and other jpg into project. I don't know if I need drag this jpg into the project, but the code didn't work either way, before and after dragging.
[UIImage imageNamed] will load the file with the given name from the app bundle; what you want is [UIImage imageWithContentsOfFile] (reference).
Also you need to understand that relative file paths work based on the process's current working directory. Do you know what that is? If not then you can log it using something like:
char cwd[1024];
getcwd(cwd, sizeof(cwd));
NSLog(#"cwd='%s'", cwd);
(You may need to #import <unistd.h>).
Perhaps that will help you with your relative path issue.

Get path of dropped file in cocoa application

I wondering how you would retrieve the path of the file that a user has dragged and dropped into a cocoa application. For example: User drags a file named test from his/her desktop. Then the cocoa application would say: Users/currentusername/Desktop/test
Thanks for the help!
I just downloaded Apple's "CocoaDragAndDrop" sample code and tried it out.
When I drag in a PNG file from the Finder into the running app, the title of the window changes to the path of the image that was dragged in.
Looking inside the sample code, I can see a file URL is included in the Pasteboard:
//if the drag comes from a file, set the window title to the filename
fileURL=[NSURL URLFromPasteboard: [sender draggingPasteboard]];
[[self window] setTitle: fileURL!=NULL ? [fileURL absoluteString] : #"(no name)"];
Try this technique in your own code and modify it for taste.
The accepted answer is no longer working with Xcode 6.
I've found this methode to get the same result:
NSURL*fileURL = [NSURL URLFromPasteboard: [sender draggingPasteboard]];
NSString *filePath = [fileURL path];
[[self window] setTitle:filePath];
Currently working on developing a similar interface, I’ve understood that the OP had asked for path, not URL retrieval. It seems the suggested OS X 10.10 (XCode6) workaround for the accepted answer has issues in refusing to drag and drop content between windows.
However, avoiding declaring NSString *filePath, but simply substituting the [fileURL absoluteString] method with [fileURL path] method in line 175 of DragDropImageView.m of the suggested sample code instead, seems to solve it:
fileURL=[NSURL URLFromPasteboard: [sender draggingPasteboard]];
[[self window] setTitle: fileURL!=NULL ? [fileURL path] : #"(no name)"];
It compiles and runs as devised in Xcode4 through Xcode6, SDK 10.8-10.10, AFAICT.
Hope this can help.

Problems with nsstring from file local

I am making an iphone app and I want to be able to load high scores from text files. I made a file called highscores1.txt and added it to my xcode project. When I try to make an NSString from the text in the file, the NSString's value is nil. Here is my code:
NSString *highscore1 = [NSString stringWithContentsOfFile:#"highscore1.txt" encoding:NSUTF8StringEncoding error:NULL];
I tried changing the file path to its complete path like this:
NSString *highscore1 = [NSString stringWithContentsOfFile:#"/Users/deepikama/Documents/games/Dodge Cars/Dodge Cars/highscore1.txt" encoding:NSUTF8StringEncoding error:NULL];
And this results in the value that I was intending to find. Why does the complete path work but not the local path? How can I make the local path work as well?
I think this explains what you need:
http://www.techotopia.com/index.php/Working_with_Directories_on_iOS_4_(iPhone)#Identifying_the_Documents_Directory
Also, I'm betting that what worked for you was only run on the simulator, and not on an actual device (where the directory structure is different).
I found a way to get it locally. I changed my code to this:
NSString *filePath = [[NSBundle mainBundle] pathForResource:#"highscore1" ofType:#"txt"];
NSString *highscore1 = [NSString stringWithContentsOfFile:filePath encoding:NSUTF8StringEncoding error:NULL];
Thanks for the help anyway.
When you added that file to your project in XCode, did you select Copy items into destination group's folder

How can I load an NSImage representation of the icon for my application?

I have a custom icon file (MyApp.icns) set up for my Cocoa App. How can I access an NSImage representation of the icon from within my application?
Something like the following would be perfect:
NSImage * iconImage = [MyApplication defaultIconAsImage];
But I'm sure it isn't that easy :)
I can, of course, get a path to the icon file as follows:
NSString * iconPath = [[NSBundle mainBundle]
pathForResource:#"MyApp" ofType:#"icns"];
But it seems to me that there should be some kind of standard way to access the icon file for the application, other than calling it by name, since the name could change.
What is the proper way to do this?
[NSApp applicationIconImage]
Just for completeness - This is how you get the icon for any application or file on your system.
NSImage *iconImage = [[NSWorkspace sharedWorkspace] iconForFile:#"path"];
Pass in the path to the application bundle for an application icon or the path to a file for the icon associated with the file.
Note that -[NSApplication applicationIconImage] doesn't return the correct icon when a custom icon is pasted onto the app. Then you need to do:
NSString* appPath = [[NSBundle mainBundle] bundlePath];
NSImage* appIcon = [[NSWorkspace sharedWorkspace] iconForFile:appPath];
(Reference the dock icon code I wrote for Chromium: http://src.chromium.org/svn/trunk/src/chrome/browser/ui/cocoa/dock_icon.mm)

How do I handle multiple file drag/drop from Finder in Mac OS X 10.5?

I need to get the URLs of all files dragged/dropped into my application from Finder.
I have a Cocoa app running on 10.6 which does this by using the new 10.6 NSPasteboard APIs which handle multiple items on the pasteboard. I'm trying to backport this app to 10.5. How do I handle this on 10.5?
If I do something like below, I only get the first URL:
NSArray *pasteTypes = [NSArray arrayWithObjects: NSURLPboardType, nil];
NSString *bestType = [pboard availableTypeFromArray:pasteTypes];
if (bestType != nil) {
NSURL *url = [NSURL URLFromPasteboard:pboard];
}
Getting multiple filenames is easy: (While getting multiple URLs is not with 10.5)
Register your view for
NSFilenamesPboardType
In performDragOperation: do the following to get an array of file paths:
NSPasteboard* pboard = [sender draggingPasteboard];
NSArray* filenames = [pboard propertyListForType:NSFilenamesPboardType];
The IKImageKit programming topics outline a way to do this like so (paraphrased):
NSData *data = [pasteboard dataForType:NSFilenamesPboardType];
NSArray *filenames = [NSPropertyListSerialization
propertyListFromData:data
mutabilityOption:kCFPropertyListImmutable
format:nil
errorDescription:&errorDescription];
See here: Image Kit Programming Guide: Supporting Drag and Drop
The NSURLPboardType just handles one URL.
To get a list of files you need to create a NSArray from a NSFilenamesPboardType.
Apple's docs on drag and drop are pretty good, even if it's older stuff.
How do I handle [multiple items on a pasteboard] on 10.5?
Try the Pasteboard Manager.
The tricky part is that you're handling a drop, which means you're receiving an NSPasteboard already created for you, and there's no way to convert between NSPasteboard objects and PasteboardRefs. You'll have to ask the NSPasteboard for its name, then pass the same name to PasteboardCreate, and that may not work.
my two cents for swift 5.1 (drop in NSView... to be customized)
see at:
Swift: Opening a file by drag-and-drop in window

Resources