在 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
}
})
您可以 dispatchMain() 在 main 的末尾调用。这将运行 GCD 主队列调度程序并且永不返回,因此它将阻止主线程退出。然后,您只需要 exit() 在准备就绪时明确调用以退出应用程序(否则命令行应用程序将挂起)。
import Foundation
let url = URL(string:"http://www..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()
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")
// signals the process to continue
sema.signal()
}
task.resume()
// sets the process to wait
sema.wait()
// 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))
}