在swift 2命令行工具(main.swift)中,我有以下内容:
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
}
})
控制台显示' yay'然后退出(程序以退出代码结束:0),似乎没有等待请求完成。我该如何防止这种情况发生?
代码正在使用swiftHTTP
我想我可能需要NSRunLoop,但没有快捷的例子
答案 0 :(得分:22)
将NSRunLoop.mainRunLoop().run()
添加到文件末尾是一个选项。有关使用信号量here
答案 1 :(得分:12)
我意识到这是一个老问题,但这是我最后解决的方法。使用DispatchGroup。
let dispatchGroup = DispatchGroup()
for someItem in items {
dispatchGroup.enter()
doSomeAsyncWork(item: someItem) {
dispatchGroup.leave()
}
}
dispatchGroup.notify(queue: DispatchQueue.main) {
exit(EXIT_SUCCESS)
}
dispatchMain()
答案 2 :(得分:10)
您可以在主页结束时致电dispatchMain()
。它运行GCD主队列调度程序并且永远不会返回,因此它将阻止主线程退出。然后,您只需要在准备就绪时显式调用exit()
以退出应用程序(否则命令行应用程序将挂起)。
import Foundation
let url = URL(string:"http://www.stackoverflow.com")!
let dataTask = URLSession.shared.dataTask(with:url) { (data, response, error) in
// handle the network response
print("data=\(data)")
print("response=\(response)")
print("error=\(error)")
// explicitly exit the program after response is handled
exit(EXIT_SUCCESS)
}
dataTask.resume()
// Run GCD main dispatcher, this function never returns, call exit() elsewhere to quit the program or it will hang
dispatchMain()
答案 3 :(得分:6)
不要依赖时间..你应该试试这个
let sema = DispatchSemaphore( value: 0)
let url = URL(string: "https://upload.wikimedia.org/wikipedia/commons/4/4d/Cat_November_2010-1a.jpg")!;
let task = URLSession.shared.dataTask(with: url) { (data, response, error) in
print("after image is downloaded");
sema.signal(); // signals the process to continue
};
task.resume();
sema.wait(); // sets the process to wait
答案 4 :(得分:3)
如果您需要不某些需要“生产级别”代码但某些快速实验或试用一段代码的内容,您可以这样做:
SWIFT 3
//put at the end of your main file
RunLoop.main.run(until: Date(timeIntervalSinceNow: 15)) //will run your app for 15 seconds only
更多信息:https://stackoverflow.com/a/40870157/469614
请注意您不应该依赖架构中的固定执行时间。
答案 5 :(得分:2)
快速键4:RunLoop.main.run()
文件结尾
答案 6 :(得分:0)
// Step 1: Add isDone global flag
var isDone = false
// Step 2: Set isDone to true in callback
request.GET(...) {
...
isDone = true
}
// Step 3: Add waiting block at the end of code
while(!isDone) {
// run your code for 0.1 second
RunLoop.main.run(until: Date(timeIntervalSinceNow: 0.1))
}