简体   繁体   English

使用URLSession的本地网络-Swift 4.2,Xcode 10.1

[英]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. 我正在尝试通过本地网络向IP地址发出HTTP请求。 However, when I call dataTask it doesn't actually make the request. 但是,当我调用dataTask时,它实际上并没有发出请求。 Requests to the internet work fine. 对互联网的请求工作正常。 I also tried making the request from HTTPBot and it was successful. 我还尝试了从HTTPBot发出请求,该请求成功。

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 网址已正确定义为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. 我试图逐步解决它,但是在命中URLSession.shared.dataTask之后,它什么也没做。 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. 我怀疑存在线程问题,并尝试添加延迟,以及尝试从全局线程分派dataTask,但均无济于事。 I also tried to allow arbitrary loads in my .plist file and add that IP as an exception domain: 我还尝试允许在.plist文件中进行任意加载,并将该IP添加为异常域: plist中

I'm not sure what I'm missing. 我不确定我缺少什么。

According to the Apple documentation : 根据Apple文档

After you create the task, you must start it by calling its resume() method. 创建任务后,必须通过调用它的resume()方法来启动它。

So you have to hold onto the URLSession.shared.dataTask instance and start it with the resume method. 因此,您必须保留URLSession.shared.dataTask实例,并使用resume方法启动它。 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()

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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