How to check validity of URL in Swift?

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

    I found this one clean (In Swift):

    func canOpenURL(string: String?) -> Bool {
        guard let urlString = string else {return false}
        guard let url = NSURL(string: urlString) else {return false}
        if !UIApplication.sharedApplication().canOpenURL(url) {return false}
    
        //
        let regEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
        let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[regEx])
        return predicate.evaluateWithObject(string)
    }
    

    Usage:

    if canOpenURL("abc") {
        print("valid url.")
    } else {
        print("invalid url.")
    }
    

    ===

    for Swift 4.1:

    func canOpenURL(_ string: String?) -> Bool {
        guard let urlString = string,
            let url = URL(string: urlString)
            else { return false }
    
        if !UIApplication.shared.canOpenURL(url) { return false }
    
        let regEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
        let predicate = NSPredicate(format:"SELF MATCHES %@", argumentArray:[regEx])
        return predicate.evaluate(with: string)
    }
    
    // Usage
    if canOpenURL("abc") {
        print("valid url.")
    } else {
        print("invalid url.") // This line executes
    }
    
    if canOpenURL("https://www.google.com") {
        print("valid url.") // This line executes
    } else {
        print("invalid url.")
    }
    

提交回复
热议问题