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
Related
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.
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.
How can i get nsstring from NSURL from this panel to use it with another action too?
arxeio = myPanel.URL.lastPathComponent;
myPanel.URL.lastPathComponent is an NSString.
If you want the whole URL, use [myPanel.URL absoluteString].
Newbie here (as may be evident by the question) but after many many hours of trying to figure this one out I have hit a point I need to ask for help...
Basically, all I want to do is parse a string from an array populated within a .plist. This string being a local URL. It works perfectly for external URL's, but no matter what I have tried for a local URL, all I get is nothing - Not even a URL not found (I lie - that did happen once but to never again be replicated).
Any and all help will be greatly appreciated!
I have this code in DetailViewController:
NSString *attractionURL = [detailItem description];
NSURL *url = [NSURL URLWithString:attractionURL];
[wikiView loadRequest:[NSURLRequest requestWithURL:url]];
And this code in a popOver (RootViewController):
- (void)viewDidLoad {
[super viewDidLoad];
self.clearsSelectionOnViewWillAppear = NO;
self.contentSizeForViewInPopover = CGSizeMake(320.0, 600.0);
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle pathForResource:#"recipes"
ofType:#"plist"];
attractions = [[NSArray alloc] initWithContentsOfFile:path];
self.title = #"Recipes";
With the URL's in a .plist file:
<array>
<array>
<string>Sirloin</string>
<string>http://Resources/iPad/index.html</string>
</array>
<array>
<string>Chasseur</string>
<string>http://www.jamesmartinsfood.com</string>
</array>
</array>
</plist>
Like I say, external URL works fine, local just doesn't do squat...
Cheers!
Your local URL isn't defined properly, it shouldn't have http:// as it is not hosted on an http server.
It should be in a format like the following.
file://localhost/var/mobile/Application/${APP_ID}/MyApp.app/index.html
The first part is potentially ever changing based on device/environment and you will need to rely on the OS Framework to determine it, so in your plist you would only define the relative path to the local files and then prepend the path provided by the OS.
Something along the lines of
NSString *path = [[NSBundle mainBundle] pathForResource:myFileName ofType:myFileExtension];
Might work for you, where you myFileName is "index" and myFileExtension is "html"
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"];