How to check validity of URL in Swift?

后端 未结 22 1787
不知归路
不知归路 2020-11-29 02:05

Trying to make an app launch the default browser to a URL, but only if the URL entered is valid, otherwise it displays a message saying the URL is invalid.

How would

22条回答
  •  甜味超标
    2020-11-29 02:20

    2020, I was tasked on fixing a bug of a method for underlining string links within a string. Most of the answers here don't work properly (try: aaa.com.bd or aaa.bd) These links should be valid. And then I stumbled upon the regex string for this.

    Ref: https://urlregex.com/

    So based on that regex

    "((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?"
    

    We can write a function.

    SWIFT 5.x:

    extension String {
        var validURL: Bool {
            get {
                let regEx = "((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?"
                let predicate = NSPredicate(format: "SELF MATCHES %@", argumentArray: [regEx])
                return predicate.evaluate(with: self)
            }
        }
    }
    

    OBJECTIVE-C (write this however you want, category or not).

    - (BOOL)stringIsValidURL:(NSString *)string
    {
        NSString *regEx = @"((?:http|https)://)?(?:www\\.)?[\\w\\d\\-_]+\\.\\w{2,3}(\\.\\w{2})?(/(?<=/)(?:[\\w\\d\\-./_]+)?)?";
        NSPredicate *predicate = [NSPredicate predicateWithFormat:@"SELF MATCHES %@" argumentArray:@[regEx]];
        return [predicate evaluateWithObject:string];
    }
    

提交回复
热议问题