Swift: Verifying is valid url in OS X playground

孤人 提交于 2019-12-13 01:25:03

问题


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"))

I'll really appreciate your help.


回答1:


There's two things to check: if the URL itself is valid, and if the server responds without error.

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)
    }
}

Usage:

verifyURL("http://google.com") { (isValid) in
    print(isValid)
}

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



回答2:


You rather need to do following check:

func validateUrl (urlString: String?) -> Bool {

    let url: NSURL? = NSURL(string: urlString!)

    if url != nil {
        return true
    }
    return false
}

print (validateUrl("http://google.com"))
print (validateUrl("http:/ /google.com"))


来源:https://stackoverflow.com/questions/37126085/swift-verifying-is-valid-url-in-os-x-playground

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!