matteodv matteodv - 4 months ago 13
iOS Question

Check if an URL has got http:// prefix

In my application, when the user add an object, can also add a link for this object and then the link can be opened in a webView.

I tried to save a link without http:// prefix, then open it in the webView but that can't open it!

Before webView starts loading, is there a method to check if the URL saved has got http:// prefix? And if it hasn't got it, how can I add the prefix to the URL?



You can use the - (BOOL)hasPrefix:(NSString *)aString method on NSString to see if an NSString containing your URL starts with the http:// prefix, and if not add the prefix.

NSString *myURLString = @"";
if ([myURLString.lowercaseString hasPrefix:@"http://"]) {
    myURL = [NSURL URLWithString:myURLString];
} else {
    myURL = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@",myURLString]];

I'm currently away from my mac and can't compile/test this code, but I believe the above should work.