views:

111

answers:

3

Is there some blindingly obvious reason why this is producing a nil string instead of the actual text content of the file?

NSString *fromFile = [NSString stringWithContentsOfFile:
                       @"file://localhost/Users/username/Desktop/test.txt"];

NSLog(@"%@", fromFile);

PRINTS: "(null)"

The file is a plain ASCII text file saved from TextWrangler with contents ' abc '.

The path comes from dragging the actual file from the desktop into the Xcode editor window.

I've also tried without "file://localhost".

The method documentation says "Returns nil if the file can't be opened". There's nothing unusual about the file (not locked, etc.). It has default Unix permissions and was created by the same user as is running Xcode.

I know this method is deprecated -- trying to get this working first.

A: 

are you running a webserver otherwise the file location is c:\ etc instead of localhost

Grumpy
Mac not Windows...
A: 

Have you tried ~/Desktop/test.txt or /Users/username/Desktop/test.txt?

jessecurry
Well I *thought* I had, for sure, 3 times. And now indeed /Users/username/Desktop/test.txt is working. But BTW ~/Desktop/test.txt doesn't work.
you would probably need to call NSString's stringByExpandingTildeInPath method to make the second one work, sorry about that.
jessecurry
+3  A: 

You have stringWithContentsOfFile: and stringWithContentsOfURL: mixed up.

If you are passing in a URL e.g. @"file://localhost/Users/username/Desktop/test.txt" the you want stringWithContentsOfURL: and make the parameter a NSURL e.g. [NSURL URLWithString:@"file://localhost/Users/username/Desktop/test.txt"]

If you want to use stringWithContentsOfFile: the the parameter should be @"/Users/username/Desktop/test.txt"

Mark
Strangely "file://localhost/..." is what Xcode produces if you drag the file itself into the Xcode editor window. The /Users/... path does work... Thanks.
Note that stringWithContentsOfURL doesn't seem to work with "file://localhost" either -- produces warning about distinct Objective-C type (??).
Ah misread the docs - the parameter is a NSURL - edited for that - however always test code ;(
Mark