gpt4 book ai didi

ios - 在执行下一个操作之前等待请求完成

转载 作者:可可西里 更新时间:2023-11-01 00:58:17 25 4
gpt4 key购买 nike

我想知道如何在执行另一段代码之前等待发送请求以完成上传(并获得响应)的操作。我试图用 NSOperations 来做到这一点:

    let testOp = BlockOperation {
var result = 0

for i in 1...1000000000 {
result += i
}
}

let logOp = BlockOperation {
self.debug.log(tag: "test", content: "testing")
}

logOp.completionBlock = {
print("------- logOp completed")
}

logOp.addDependency(testOp)

let sendOp = BlockOperation {
self.debug.sendLog() //uploads log, using URLSession.shared.dataTask
}

sendOp.completionBlock = {
print("------- sendOp completed")
}

sendOp.addDependency(logOp)

let emptyOp = BlockOperation {
self.debug.empty()
}

emptyOp.completionBlock = {
print("------- emptyOp completed")
}

emptyOp.addDependency(sendOp)

let queue = OperationQueue()
queue.addOperations([testOp, logOp, sendOp, emptyOp], waitUntilFinished: false)

输出:

------- logOp completed
*** Sending debug log (coming from self.debug.sendLog())
------- sendOp completed
------- emptyOp completed
*** sendLog uploaded (coming from self.debug.sendLog())

根据我的代码,我预计输出为:

------- logOp completed
*** Sending debug log
*** sendLog uploaded
------- sendOp completed
------- emptyOp completed

我如何做到这一点?我可以用 NSOperations 做到这一点吗?

有关 debug.sendLog() 函数的其他详细信息:

func sendLog() {
...
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "POST"
...

let session = URLSession.shared
let task = session.dataTask(with: urlRequest, completionHandler: {
(data, response, error) in

...

DispatchQueue.main.async {
print("*** sendLog uploaded")

}
})

task.resume()
}

最佳答案

您可以将完成 block 直接添加到 sendLog 方法并抛弃所有 block 操作内容。

func sendLog(withCompletion completion: (() -> Void)) {
...
var urlRequest = URLRequest(url: url!)
urlRequest.httpMethod = "POST"
...

let session = URLSession.shared
let task = session.dataTask(with: urlRequest, completionHandler: {
(data, response, error) in

...
completion?()
})

task.resume()
}

然后像这样调用您的sendLog方法:

sendLog(withCompletion: {
// Execute the code you want to happen on completion here.
})

关于ios - 在执行下一个操作之前等待请求完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39899105/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com