user2924482
user2924482

Reputation: 9120

Swift: Verifying is valid url in OS X playground

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.

Upvotes: 2

Views: 1043

Answers (2)

Eric Aya
Eric Aya

Reputation: 70098

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

Upvotes: 2

Igor B.
Igor B.

Reputation: 2229

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

Upvotes: -1

Related Questions