Ehsan
Ehsan

Reputation: 63

Local networking using URLSession - Swift 4.2, Xcode 10.1

I am trying to make an HTTP request over the local network to an IP address. However, when I call dataTask it doesn't actually make the request. Requests to the internet work fine. I also tried making the request from HTTPBot and it was successful.

Here's the code that's making the call:

    let url = apiBaseUrl + "get_serial"
    let urlObj = URL(string: url)
    var urlRequest = URLRequest(url: urlObj!)

    urlRequest.httpMethod = "GET"
    urlRequest.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData

    URLSession.shared.dataTask(with: urlObj!) { (data, response, error) in
            guard let data = data else { return }

            let serial = (String(data: data, encoding: .utf8))

            onSuccess(serial ?? "")
        }

The url is correctly defined as http://192.168.0.50/get_serial

I tried to step through it, but after it hits URLSession.shared.dataTask it doesn't do anything else. I suspected a threading issue and tried adding a delay, as well as trying to dispatch the dataTask from the global thread, but neither worked. I also tried to allow arbitrary loads in my .plist file and add that IP as an exception domain: plist

I'm not sure what I'm missing.

Upvotes: 0

Views: 1969

Answers (1)

Charlie Fish
Charlie Fish

Reputation: 20536

According to the Apple documentation:

After you create the task, you must start it by calling its resume() method.

So you have to hold onto the URLSession.shared.dataTask instance and start it with the resume method. Something like the following.

let url = apiBaseUrl + "get_serial"
let urlObj = URL(string: url)
var urlRequest = URLRequest(url: urlObj!)

urlRequest.httpMethod = "GET"
urlRequest.cachePolicy = URLRequest.CachePolicy.reloadIgnoringCacheData

let task = URLSession.shared.dataTask(with: urlObj!) { (data, response, error) in
        guard let data = data else { return }

        let serial = (String(data: data, encoding: .utf8))

        onSuccess(serial ?? "")
    }

task.resume()

Upvotes: 1

Related Questions