Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you test a URL and get a status code in Swift 3?

Tags:

swift

swift3

I'm using the most recent version of Xcode (8.1 at time of writing), which uses Swift 3.0.

All I'm trying to do is take a string, convert it to a URL and test that URL to see if it gives me a 404 error. I've been able to make a URL and URLRequest by using:

    let url = URL(string: fullURL)
    let request = URLRequest(url: url!)

but I've found myself unable to get anything working beyond that. I've searched around for help, but most, if not all of it, is written in Swift 2.0, which I've tried to convert to no avail. It seems that even if you change the naming convention to remove the NS prefix, that isn't enough. I tried using:

    let response: AutoreleasingUnsafeMutablePointer<URLRequest> = nil

but that gives me an error that "fix-it" makes worse by sticking question marks and semi-colons everywhere.

Apple's documentation isn't helping me much, either. I'm seriously at a loss.

Does anybody know how to correctly set up and test a URL for 404 status in Swift 3.0?

like image 613
DisturbedNeo Avatar asked Nov 02 '16 14:11

DisturbedNeo


2 Answers

try this out to give you the status codes of the responses - 200, 404 etc:

let url = URL(string: fullURL)

let task = URLSession.shared.dataTask(with: url!) { _, response, _ in
    if let httpResponse = response as? HTTPURLResponse {
        print(httpResponse.statusCode)
    }
}

task.resume()

You could also do the same, simply replacing the with: url! to use the request var as you defined in your example e.g. let task = URLSession.shared.dataTask(with: request) {...} But in this example I don't think you need to really.

like image 168
Matt Le Fleur Avatar answered Oct 21 '22 09:10

Matt Le Fleur


Simple example:

    let url = // whatever
    let session = URLSession.shared
    let task = session.downloadTask(with:url) { loc, resp, err in
        let status = (resp as! HTTPURLResponse).statusCode
        print("response status: \(status)")
    }
    task.resume()
like image 27
matt Avatar answered Oct 21 '22 08:10

matt