How to check validity of URL in Swift?

后端 未结 22 1784
不知归路
不知归路 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:14

    Swift 5.1 Solution

    extension String {
        func canOpenUrl() -> Bool {
            guard let url = URL(string: self), UIApplication.shared.canOpenURL(url) else { return false }
            let regEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
            let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[regEx])
            return predicate.evaluate(with: self)
        }
    }
    

提交回复
热议问题