Swift:在OS X Playground中验证有效的URL [英] Swift: Verifying is valid url in OS X playground
本文介绍了Swift:在OS X Playground中验证有效的URL的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在尝试验证/验证url,但是当我这样做时,它总是打开safari。你们当中任何人都知道没有公开的野生动物园怎么能做到这一点。这是我的代码:
I'm trying to verify/validate url but when I do it always opens safari. Any of you know how can accomplish this without open safari. Here is my code:
func validateUrl (urlString: String?) -> Bool {
let url:NSURL = NSURL(string: urlString!)!
if NSWorkspace.sharedWorkspace().openURL(url) {
return true
}
return false
}
print (validateUrl("http://google.com"))
非常感谢您
推荐答案
有两点要检查:URL 本身是否有效,以及服务器响应没有错误。
There's two things to check: if the URL itself is valid, and if the server responds without error.
在我的示例中,我使用的是HEAD请求,它避免了下载整个页面,并且几乎不占用带宽。
In my example I'm using a HEAD request, it avoids downloading the whole page and takes almost no bandwidth.
func verifyURL(urlPath: String, completion: (isValid: Bool)->()) {
if let url = NSURL(string: urlPath) {
let request = NSMutableURLRequest(URL: url)
request.HTTPMethod = "HEAD"
let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { (_, response, error) in
if let httpResponse = response as? NSHTTPURLResponse where error == nil && httpResponse.statusCode == 200 {
completion(isValid: true)
} else {
completion(isValid: false)
}
}
task.resume()
} else {
completion(isValid: false)
}
}
用法:
verifyURL("http://google.com") { (isValid) in
print(isValid)
}
用于游乐场,不要忘记启用异步模式以便能够使用NSURLSession:
For use in a Playground, don't forget to enable the asynchronous mode in order to be able to use NSURLSession:
import XCPlayground
XCPlaygroundPage.currentPage.needsIndefiniteExecution = true
这篇关于Swift:在OS X Playground中验证有效的URL的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文