How to check validity of URL in Swift?

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

    Swift 4.2 Elegant URL construction with verification

    import Foundation
    import UIKit
    
    extension URL {
    
      init?(withCheck string: String?) {
        let regEx = "((https|http)://)((\\w|-)+)(([.]|[/])((\\w|-)+))+"
        guard
            let urlString = string,
            let url = URL(string: urlString),
            NSPredicate(format: "SELF MATCHES %@", argumentArray: [regEx]).evaluate(with: urlString),
            UIApplication.shared.canOpenURL(url)
            else {
                return nil
        }
    
        self = url
      }
    }
    

    Usage

    var imageUrl: URL? {
        if let url = URL(withCheck: imageString) {
            return url
        }
        if let url = URL(withCheck: image2String) {
            return url
        }
        return nil
    }
    

提交回复
热议问题