northsydneybears
northsydneybears

Reputation: 31

Checking user inputted URLs in Objective C/XCode 6 - NSRangeException

G'day,

I'm attempting to check user-inputted URLs in a browser app. The aim is to add the http:// etc scheme if the user doesn't input it, and to assume they're after a Google search if they include any spaces within the text field.

I think I'm just about there but am crashing due to the following error whenever I type in something that isn't a complete URL and doesn't have spaces. Put simply,

Terminating app due to uncaught exception 'NSRangeException', reason: '-[__NSCFString replaceCharactersInRange:withString:]: Range or index out of bounds'

I've looked at the following similar questions with no luck:

How to validate an(sic) url on the iphone

Checking if a string is a url objective c

NSRange crashing app

This question is very similar to mine but wasn't quite answered:

Correcting user submitted url in xcode objective c

Please find my code below

- (BOOL)textFieldShouldReturn:(UITextField *)textField {
[textField resignFirstResponder];

NSString *URLString = textField.text;

NSURL *URL = [NSURL URLWithString:URLString];

if (!URL.scheme) {

    NSRange urlSpace = [URLString rangeOfString:@" "];
    NSString *urlNoSpace = [URLString stringByReplacingCharactersInRange:urlSpace withString:@"+"];

    if (urlSpace.location != NSNotFound) {
    // The user typed a space so we assume it's a search engine query
        URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://www.google.com/search?q=%@", urlNoSpace]];
    } else {
    // The user didn't type http: or https: for the scheme
        URL = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", URLString]];
    }
}

if (URL) {
    NSURLRequest *request = [NSURLRequest requestWithURL:URL];
    [self.webview loadRequest:request];
}

return NO;

}

Thank you for any help you can provide, much appreciated!

Upvotes: 1

Views: 581

Answers (1)

rmaddy
rmaddy

Reputation: 318804

If the URL doesn't have a space, then urlSpace will have a location of NSNotFound and a length of 0 (or is it -1?).

You need to check this before using the range to create urlNoSpace.

Since you really want to change all spaces why not simply do:

NSString *urlNoSpace = [URLString stringByReplacingOccurrencesOfString:@" " withString:@"+"];

This fixes two problems: your crash and it replaces all spaces, not just the first one.

Upvotes: 1

Related Questions