Check if an URL has got http:// prefix
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.
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)}