views:

93

answers:

3

Hi,
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?
Thanks!

+2  A: 

I am not sure if there is any method to check that but you check it in the code.

try using NSRange range = [urlString rangeOfString:@"http://"]; if (range.location != NSNotFound) // Add http://

KiranThorat
+2  A: 

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 = @"www.google.com";
NSURL *myURL;
if ([myURLString 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.

GregInYEG
This test breaks with "HTTP://www.google.com". It also doesn't support ftp://, even though UIWebView does.
tc.
I think my answer gives sufficient information that Matthew can solve his problem.
GregInYEG
Yes Greg, that's what I'm looking for... I'll support only http protocol because it's the only one that can serve in my app... ;)
Matthew
+2  A: 
NSString * urlString = ...;
NSURL * url = [NSURL URLWithString:urlString];
if (![[url scheme] length])
{
  url = [NSURL URLWithString:[@"http://" stringByAppendingString:urlString]];
}
tc.
This can be a solution but this method add the http:// to the URL... and if the URL has got http:// what do this method?
Matthew
This code adds "http://" to all URLs without a scheme. "http://blah" has the scheme "http", so `[[url scheme] length]` is non-zero and the code leaves the URL as-is.
tc.