如何防止命令行工具在异步操作完成之前退出 [英] How to prevent a Command Line Tool from exiting before asynchronous operation completes
本文介绍了如何防止命令行工具在异步操作完成之前退出的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在swift 2命令行工具(main.swift)中,我具有以下内容:
In a swift 2 command line tool (main.swift), I have the following:
import Foundation
print("yay")
var request = HTTPTask()
request.GET("http://www.stackoverflow.com", parameters: nil, completionHandler: {(response: HTTPResponse) in
if let err = response.error {
print("error: \(err.localizedDescription)")
return //also notify app of failure as needed
}
if let data = response.responseObject as? NSData {
let str = NSString(data: data, encoding: NSUTF8StringEncoding)
print("response: \(str)") //prints the HTML of the page
}
})
控制台显示是",然后退出(程序以退出代码结束:0),似乎从未等待请求完成.我该如何防止这种情况发生?
The console shows 'yay' and then exits (Program ended with exit code: 0), seemingly without ever waiting for the request to complete. How would I prevent this from happening?
代码正在使用 swiftHTTP
I think I might need an NSRunLoop but there is no swift example
推荐答案
我意识到这是一个老问题,但这是我最后的解决方案.使用 DispatchGroup .
I realize this is an old question, but here is the solution I ended on. Using DispatchGroup.
let dispatchGroup = DispatchGroup()
for someItem in items {
dispatchGroup.enter()
doSomeAsyncWork(item: someItem) {
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: DispatchQueue.main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
这篇关于如何防止命令行工具在异步操作完成之前退出的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文