简体   繁体   English

Swift-如何在完成函数之前播放URLSession?

[英]Swift - How to play URLSession before finalizing a function?

I am currently using a URLSession to send and receive data from a web server, but I have the problem that the query is executed at the end of any other code that follows it, for example if I have the following instructions: 我当前正在使用URLSession从Web服务器发送和接收数据,但是我遇到的问题是查询是在跟在它后面的任何其他代码的末尾执行的,例如,如果我有以下说明,则为:

_ = URLSession.shared.dataTask (with: url_request) 
{(data, response, error) in
}.resume ()

print ("Hello world")

First you will run the "Hello world" and then the http query, how can I make the URLSession run and then what is left of the code? 首先,您将运行“ Hello world”,然后运行http查询,如何运行URLSession,然后剩下什么代码?

URL sessions are asynchronous and involve time in communicating back and forth to a server. URL会话是异步的,在与服务器进行来回通信时会花费一些时间。 You have to use a variant of the URLSession that allows you to have a completion handler: 您必须使用URLSession的变体,该变体允许您具有完成处理程序:

    URLSession.shared.dataTask(with: my_url) { (response_data, url_response, communication_error) in
        print ("Hello World")
    }

Good luck! 祝好运!

This is the solution I found: 这是我发现的解决方案:

let semaphore = DispatchSemaphore(value: 0)

_ = URLSession.shared.dataTask (with: url_request) 
{(data, response, error) in
   print("One")
   semaphore.signal()
}.resume ()

_ = semaphore.wait(timeout: DispatchTime.distantFuture)
print (“Two”)

And this is what prints: 这是打印的内容:

>> One
>> Two

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

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