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?
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With