Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 664
matteodv Avatar asked Sep 24 '10 16:09

matteodv


4 Answers

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.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.

like image 79
Greg Avatar answered Nov 11 '22 22:11

Greg


NSString * urlString = ...;
NSURL * url = [NSURL URLWithString:urlString];
if (![[url scheme] length])
{
  url = [NSURL URLWithString:[@"http://" stringByAppendingString:urlString]];
}
like image 24
tc. Avatar answered Nov 11 '22 20:11

tc.


Better to use the scheme property on the URL object:

extension URL {
    var isHTTPScheme: Bool {
        return scheme?.lowercased().contains("http") == true // or hasPrefix
    }
}

Example usage:

let myURL = URL(string: "https://stackoverflow.com/a/48835119/1032372")!
if myURL.isHTTPScheme {
    // handle, e.g. open in-app browser:            
    present(SFSafariViewController(url: url), animated: true)
} else if UIApplication.shared.canOpenURL(myURL) {
    UIApplication.shared.openURL(myURL)
}
like image 6
shim Avatar answered Nov 11 '22 21:11

shim


I wrote an extension for String in Swift, to see if url string got http or https

extension String{

    func isValidForUrl()->Bool{

        if(self.hasPrefix("http") || self.hasPrefix("https")){
            return true
        }
        return false
    }
}

if(urlString.isValidForUrl())
    {
      //Do the thing here.
}
like image 4
anoop4real Avatar answered Nov 11 '22 21:11

anoop4real