16


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!

Matjan
  • 3,591
  • 1
  • 33
  • 31
matteodv
  • 3,992
  • 5
  • 39
  • 73

9 Answers9

43

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.

Felix Lapalme
  • 1,058
  • 1
  • 11
  • 25
Greg
  • 33,450
  • 15
  • 93
  • 100
  • 1
    This test breaks with "HTTP://www.google.com". It also doesn't support ftp://, even though UIWebView does. – tc. Sep 25 '10 at 01:26
  • 5
    I think my answer gives sufficient information that Matthew can solve his problem. – Greg Sep 25 '10 at 15:58
  • 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... ;) – matteodv Sep 25 '10 at 16:26
  • For checking case insensitive prefix use this: http://stackoverflow.com/a/18264768/1162959 – bobics Aug 16 '13 at 02:16
16
NSString * urlString = ...;
NSURL * url = [NSURL URLWithString:urlString];
if (![[url scheme] length])
{
  url = [NSURL URLWithString:[@"http://" stringByAppendingString:urlString]];
}
tc.
  • 33,468
  • 5
  • 78
  • 96
  • 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? – matteodv Sep 25 '10 at 15:14
  • 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. Sep 26 '10 at 11:55
6

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)
}
shim
  • 9,289
  • 12
  • 69
  • 108
4

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.
}
anoop4real
  • 7,598
  • 4
  • 53
  • 56
3

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://  
Undo
  • 25,519
  • 37
  • 106
  • 129
k-thorat
  • 4,873
  • 1
  • 27
  • 36
1

If you're checking for "http://" you'll probably want case-insensitive search:

// probably better to check for just http instead of http://
NSRange prefixRange = 
    [temp rangeOfString:@"http" 
                options:(NSAnchoredSearch | NSCaseInsensitiveSearch)];
if (prefixRange.location == NSNotFound)

Although I think the url scheme check is a better answer depending on your circumstances, as URLs can begin with http or https and other prefixes depending on what your use case is.

bobics
  • 2,301
  • 2
  • 23
  • 25
0

First, you should create a new category for NSURL: File > New File > Objective-C Category. You can call the category something along the lines of HTTPURLWithString, make it a category of NSURL, press next and add it to your target. Then in the NSURL+HTTPURLFromString.m implement the following message (and declare the message in your .h)

@implementation NSURL (HTTPURLFromString)
+(NSURL *)HTTPURLFromString:(NSString *)string
{
    NSString *searchString = @"http";
    NSRange prefixRange = [string rangeOfString:searchString options:(NSCaseInsensitiveSearch | NSAnchoredSearch)];

    if (prefixRange.length == 4) {
        return [NSURL URLWithString:string];
    }
    return [NSURL URLWithString:[NSString stringWithFormat:@"http://%@", string]];

}
@end

To open a link in the WebView is simply

NSString *urlString = @"www.google.com";
NSURL *url = [NSURL HTTPURLFromString:urlString];
NSURLRequest *request = [NSURLRequest requestWithURL:url];
[webView.mainFrame loadRequest:request];
JuJoDi
  • 14,627
  • 23
  • 80
  • 126
0

You can use scheme property for check it out. For example...

if ([yourURL.scheme isEqualToString:@"http"] || [yourURL.scheme isEqualToString:@"https"]) {
    ...
} 
d0ping
  • 462
  • 4
  • 16
0

In function 'navigationAction' of WKNavigationDelegate

    func webView(_ webView: WKWebView, decidePolicyFor navigationAction: WKNavigationAction, decisionHandler: @escaping (WKNavigationActionPolicy) -> Void) {
        if navigationAction.navigationType == .linkActivated {
            if let url = navigationAction.request.url {
                decisionHandler(.cancel)
                var urlString = url.absoluteString
                if urlString.lowercased().hasPrefix("http://") == false {
                    urlString = String(format: "http://%@", urlString)
                }

                let safariViewController = SFSafariViewController(url: url)
                presentInFullScreen(safariViewController, animated: true, completion: nil)
            } else {
                decisionHandler(.allow)
            }
        } else {
            decisionHandler(.allow)
        }
    }
Jam
  • 101
  • 4