mayonaise
mayonaise

Reputation: 129

NSURL not returning nil for one-character non-ascii strings

I have been using NSURL to do a simple URL validation, mostly to weed out non-ascii special characters, which I do not want in my particular application. I take a URL as input into an NSString, then try to create an NSURL using URLWithString. If this returns nil, the app presents an error message.

For example if I enter "あか" as input (that is two Japanese characters), then the NSURL is nil. This has been working as expected. However I recently noticed that entering a string that is contains only one single non-ASCII character, NSURL processes it and returns a URL-encoded value. So if I enter "あ" as input, the resulting NSURL is NOT nil. The absoluteString value is "%E3%81%82".

I'm wondering if this is a bug in NSURL, or some kind of loophole that I'm not understanding.

I'm using Xcode 3.2.5, and the iOS 4.2 SDK.

Upvotes: 0

Views: 504

Answers (1)

jonkroll
jonkroll

Reputation: 15722

I can't explain the behavior you are seeing above, however, if all you are trying to do is determine whether a URL string contains any non-ASCII characters, you could achieve this with the following code:

NSString *testURLString = @"http://www.googleあか.com";

NSCharacterSet* ascii = [NSCharacterSet characterSetWithRange: NSMakeRange(0, 128)];
NSCharacterSet* nonAscii = [ascii invertedSet];

if ([testURLString rangeOfCharacterFromSet:nonAscii].location != NSNotFound) {
    NSLog(@"This string contains non-ASCII characters");
}

Upvotes: 3

Related Questions