简体   繁体   中英

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM