Andrew
Andrew

Reputation: 16051

URLWithString returning nil

I have this code:

NSString *logsPath = [dataDirectoryPath stringByAppendingPathComponent:@"Logs"];

Which returns:

/var/mobile/Applications/AAAAAAAA-AAAA-AAAA-AAAA-AAAAAAAAAAAA/Documents/Mobile Documents/Data/Logs

However, doing this:

NSURL *logsURL = [NSURL URLWithString:logsPath];

returns a value of nil.

Any ideas as to why this might be?

Upvotes: 0

Views: 601

Answers (3)

j berkman
j berkman

Reputation: 19

The actual problem is that spaces are illegal in URL paths. -fileURLWithPath: works because it URI encodes the space, not because it adds a scheme.

(lldb) po [NSURL URLWithString:@"/foo bar"]
nil
(lldb) po [NSURL URLWithString:@"/foo-bar"]
/foo-bar
(lldb) po [NSURL fileURLWithPath:@"/foo bar"]
file://localhost/foo%20bar
(lldb) po [NSURL URLWithString:@"/foo%20bar"]
/foo%20bar

Upvotes: 0

Sam Baumgarten
Sam Baumgarten

Reputation: 2249

[NSURL urlWithString:logsPath] expects for the url to start with https:// or http://. [dataDirectoryPath stringByAppendingPathComponent:@"Logs"]; returns a path and not a URL. To fix this use [NSURL fileURLWithPath:logsPath]. This will add file:// to the beginning of the URL making it work. Your full code will look like this:

NSString *logsPath = [dataDirectoryPath stringByAppendingPathComponent:@"Logs"];
NSURL *logsURL = [NSURL fileURLWithPath:logsPath];

Best of luck!

Upvotes: 0

Richard J. Ross III
Richard J. Ross III

Reputation: 55533

Try using +fileURLWithPath: instead.

Because +URLWithString: expects a protocol (e.g. http://, https://, file://), it cannot build a URL.

On the other hand, +fileURLWithPath: just takes the raw path, and automatically appends the file:// protocol to the path you supply.

Upvotes: 7

Related Questions