I’m trying to convert a NSURL to a NSString to use elsewhere in my program.
Here’s my code:
- (IBAction)openExistingDocument:(id)sender {
NSOpenPanel* panel = [NSOpenPanel openPanel];
[panel setCanChooseDirectories:NO];
[panel setAllowsMultipleSelection:NO];
[panel setMessage:@"Please select a File or Folder containing your character's .png layers"];
[panel beginWithCompletionHandler:^(NSInteger result){
if (result == NSFileHandlingPanelOKButton) {
NSURL* theDoc = [[panel URLs] objectAtIndex:0];
NSString* unformattedURL = [NSString stringWithContentsOfURL:theDoc encoding:NSASCIIStringEncoding error:NULL];
NSString * formattedURL = [unformattedURL stringByReplacingOccurrencesOfString:@"file:/" withString:@""];
NSLog(@"the url says:%@", theDoc);
NSLog(@"the unformatted string says: %@", unformattedURL);
NSLog(@"the formatted string says: %@", formattedURL);
}
}];
}
When I run the program, here’s what my command line outputs:
2012-01-29 18:43:19.205 Cocos2dCharacterRigger[516:407] the url says:file://localhost/Users/*****/Desktop/mockupsite.jpg
2012-01-29 18:43:19.213 Cocos2dCharacterRigger[516:407] the unformatted string says: ÿØÿá.]Exif
2012-01-29 18:43:19.219 Cocos2dCharacterRigger[516:407] the formatted string says: ÿØÿá.]Exif
Can someone point out what I’m doing incorrectly?
You are loading the contents of the file at the URL into the string. You are loading the file as an ASCII string (which that file almost certainly is not — it’s an image) and you are ignoring any errors.
To get the actual path for the url, you send the url the
-pathmessage. So, to get a string with the path:This should print the following (based on your logs above):