Septih
Septih

Reputation: 1436

NSURL fileURLWithPath where NSString has a space

I've looked at quite a few of the related questions and cannot find a similar problem or a solution so my apologies if there is a duplicate out there somewhere.

Anyway, I'm trying to generate a file's NSURL to use with an NSXMLDocument. I have the following components:

const NSString * PROJECT_DIR = @"~/SP\\ BB/";
const NSString * STRINGS_FILE = @"Localizable.strings";

and construct the URL like so:

NSURL * stringsURL = [NSURL fileURLWithPath:[[NSString stringWithFormat:@"%@%@",PROJECT_DIR,STRINGS_FILE] stringByExpandingTildeInPath]];

however, the resulting path in the NSURL is:
file://localhost/Users/timothyborrowdale/SP2B/Localizable.strings

I have tried changing the PROJECT_DIR to

@"~/SP BB/"
@"~/SP\\\\ BB/" (changes to SP엀2B)
@"~/SP%20BB/"
@"~/SP\%20BB/"

with the same problem. I also tried typing out the file url completely and using [NSURL URLWithString:]

I have also tried using stringByAddingPercentEscapesUsingEncoding with both NSUTF8Encoding and NSASCCIEncoding and these have the same issue.

The NSString displays properly before being passed to NSURL or stringByAddingPercentEscapesUsingEncoding but has the problem once outputted from either.

Upvotes: 1

Views: 4680

Answers (2)

Jeremy W. Sherman
Jeremy W. Sherman

Reputation: 36143

Try this:

NSString *fnam = [@"Localizable" stringByAppendingPathExtension:@"strings"];
NSArray *parts = [NSArray arrayWithPathComponents:@"~", @"SP BB", fnam, (void *)nil];
NSString *path = [[NSString pathWithComponents:parts] stringByStandardizingPath];
NSURL *furl = [NSURL fileURLWithPath:path];

Foundation has a host of platform-independent, path-related methods. Prefer those over hard-coding path extension separators (often ".") and path component separators (often "/" or "\").

Upvotes: 1

Peter Hosey
Peter Hosey

Reputation: 96323

Try abandoning stringWithFormat: (never the right answer for stapling paths together) and stringByExpandingTildeInPath and using NSHomeDirectory() and stringByAppendingPathComponent: instead.

  • @"~/SP\\ BB/" (changes to SP엀2B)

How did you arrive at that conclusion?

Upvotes: 0

Related Questions