Check if an URL has got http:// prefix

2019-03-18 04:07发布


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!

8条回答
时光不老,我们不散
2楼-- · 2019-03-18 04:24

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

if ([yourURL.scheme isEqualToString:@"http"] || [yourURL.scheme isEqualToString:@"https"]) {
    ...
} 
查看更多
Emotional °昔
3楼-- · 2019-03-18 04:27

Better to use the scheme property on the URL object:

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

Example usage:

let myURL = 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)
}
查看更多
Animai°情兽
4楼-- · 2019-03-18 04:30

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.
}
查看更多
时光不老,我们不散
5楼-- · 2019-03-18 04:32

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.

查看更多
Root(大扎)
6楼-- · 2019-03-18 04:39

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.

查看更多
Deceive 欺骗
7楼-- · 2019-03-18 04:39

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://  
查看更多
登录 后发表回答