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.
Related
first time working with selecting and taking photos. I have code working that lets a user choose (or take) a profile pic and it displays in uiview in app using the delegate pattern. To persist this pic, many articles suggest you store the image on disk, not in core data, and store just the file name in core data.
I have found the following method for storing the files.
- (void)saveImage: (UIImage*)image
{
if (image != nil)
{
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,
NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
//create a file name perhaps using time and call it
NSString* path = [documentsDirectory stringByAppendingPathComponent:
[NSString stringWithString: #"profilefilename.png"] ];
NSData* data = UIImagePNGRepresentation(image);
[data writeToFile:path atomically:YES];
}
}
I am clueless, however, how and where to call this method to store the file on disk and also when and where to store in core data.
Thanks for any suggestions
First consider adding a subdirectory rather than crowding your document directory with files.
Second, add the Core Data persistence right there in the saveImage method.
Third, at what exact time to call this save method depends on your app setup. Maybe you have a save button or something similar.
If you do not know how to actually save to Core Data, your question is out of scope for this forum. You should then first do a tutorial, e.g. this one.
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.
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
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"];
This is probably a n00b question so I apologize in advance. I'm working with NSImage for the first time and basically I need to simply take a picture that is in my Resources folder, and have it display in an NSView/NSImageWell when a button is clicked.
NSImage *image = [[NSImage alloc] initWithContentsOfFile:#"tiles.PNG"];
if ( [image isValid] ) {
NSImageView *view = [[NSImageView alloc] init];
[selection setImage:image];
[selection setImageScaling:NSScaleProportionally];
}
else {
--- This line of code always activates meaning my image isn't valid
}
My only guess is that I am getting the path wrong to the image file and I have looked all over for the right way to access it. Another guess is that I have my code wrong. Anybody familiar with this? Thanks!
I work a lot more with the iPhone, but initWithContentsOfFile seems to require a full/relative path, which I assume tiles.PNG wouldn't fulfill.
I'd use the class method imageNamed:(NSString *)name, which will search your bundle for you.
You should use NSBundleManger to locate the image like so:
NSBundle *mb=[NSBundle mainBundle];
NSString *fp=[mb pathForResource:#"titles" ofType:#"PNG"];
UIImage *img=[UIImage imageWithContentsOfFile:fp];
That way you don't have to mess with internal paths yourself. Otherwise, you have to have the path relative to the final built product which is hard to create and maintain.