在 swift 2 命令行工具(main.swift)中,我有以下内容:import Foundationprint(\'yay\')var request = HTTPTask()request.GET(\'http://www..com\',参数:nil,completionH...
在 swift 2 命令行工具(main.swift)中,我有以下内容:
import Foundation
print("yay")
var request = HTTPTask()
request.GET("http://www..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 ,但没有快速示例
// 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))
}