Swift Get Web Request

import Foundation

func doHttpCall(st : String) -> Data {
    var xmlStr = Data()
    let url = URL(string: st)!
    let semaphore = DispatchSemaphore(value: 0)
    let task =  URLSession.shared.dataTask(with: url, completionHandler: {(data, response, error) in
        if let error = error {
            print("Error: \(error)")
        } else if let response = response as? HTTPURLResponse,
                  300..<600 ~= response.statusCode {
            print("Error: \(response.statusCode)")
        } else {
            xmlStr = data!
            print(String(data: xmlStr, encoding: .utf8)!)
    _ = semaphore.wait(timeout: DispatchTime.distantFuture)
    return xmlStr

All I wanted was a simple function where I could pass a URL as a parameter and receive the data from the web site in return. I thought it should be easy. And as I was trying to do it in Apple’s Swift language, I thought it would be, well, swift.

But nope. I ended up spending far more time on it than I expected.

I’m not going to go into the details, as the two or three folks who might read this site are not tech nerds in any case and have probably stopped reading by now anyway.

In practically every other language that I’ve needed to grab a web page over the years, it’s been a pretty simple matter. I was searching the web for sample code, and I found lots of sites that purported to have such code, but it wasn’t in the form of a function that I needed.

The problem had to do with asynchronous vs. synchronous coding; I wanted the latter, and the examples were nearly all of the former.

So I offer my example code at the top of this post with the caveat that I was looking for something that would work for me in my case where I’m grabbing data from a Mac on my local network that is connected to my Mac via an ethernet cable. So I’m not worried about latency and network delays and any other network subtleties. I’ll worry about them later (if ever).

The other caveat I’ll add is that I’m not a Swift programmer. Barely even a novice. I was just looking for a function for a very specific purpose and if someone finds it by doing a web search and it seems to work for them, fine. Just be warned that it’s not an example of good Swift network programming.

Leave a Reply