尝试通过应用启动默认浏览器到一个URL,但仅在输入的URL有效时,否则显示一条消息,指示该URL无效。
我该如何使用Swift检查有效性?
这是针对最新的Swift 4版本,基于Doug Amos的回答(适用于Swift 3)
public static func verifyUrl (urlString: String?) -> Bool {
//Check for nil
if let urlString = urlString {
// create NSURL instance
if let url = NSURL(string: urlString) {
// check if your application can open the NSURL instance
return UIApplication.shared.canOpenURL(url as URL)
}
}
return false
}
这里大多数答案都没有解决我的问题,所以我在这里发布了我是如何解决它的:
static func isValidDomain(domain: String?) -> Bool {
guard let domain = domain else {
return false
}
// Modified version of https://dev59.com/HF4c5IYBdhLWcg3wT4xO#49072718
let detector = try! NSDataDetector(types: NSTextCheckingResult.CheckingType.link.rawValue)
let domainWithScheme = "https://\(domain)"
if let url = URL(string: domainWithScheme),
let match = detector.firstMatch(in: domainWithScheme, options: [], range: NSRange(location: 0, length: domainWithScheme.utf16.count)) {
// it is a link, if the match covers the whole string
return match.range.length == domainWithScheme.utf16.count && url.host != nil
} else {
return false
}
}
Milan Nosáľ的回答缺少的是,它没有针对这个特定的输入进行解释:https://#view-?name=post&post.post_id=519&message.message_id=349
所以我只需添加host
检查存在和未经计划的“URL”。
//Add in "extension String"
func verifyUrl() -> Bool {
var newString = self
let index = self.index(self.startIndex, offsetBy: 4)
let mySubstring = self.prefix(upTo: index)
if mySubstring == "www." {
newString = "https://" + newString
}
if let url = NSURL(string: newString) {
return UIApplication.shared.canOpenURL(url as URL)
}
return false
}
https://localhost
是否无效,如果是,为什么? - bencextension String {
var isValidUrl: Bool {
if let url = NSURL(string: self) {
return UIApplication.shared.canOpenURL(url as URL)
}
return false
}
}
用法:
let test1 = "abc"
let isValidUrl = test1.isValidUrl
// Result of isValidUrl will be False
let test1 = "https://www.google.com/"
let isValidUrl = test1.isValidUrl
// Result of isValidUrl will be True
这个被接受的答案在我的情况下不起作用,因为URL错误且没有数据:https://debug-cdn.checkit4team.com/5/image/Y29tbW9uL2RlZmF1bHRfYXZhdGFyLnBuZw==
所以我编写了扩展来解决问题。
extension String {
var verifyUrl: Bool {
get {
let url = URL(string: self)
if url == nil || NSData(contentsOf: url!) == nil {
return false
} else {
return true
}
}
}
}
使用它:
if string. verifyUrl {
// do something
}
希望这可以帮到你!
NSData(contentsOf: url!)
发起了一个同步(阻塞)请求,它应该用于(小型)本地文件,但是当你给它网络URL时,它也会这样做。我提到了这一点,因为答案中提到的URL是基于网络的。我还提到了文档中的黄色重要框,请去阅读一下 ;) - 5keeve