完成或关闭只是一个包含在参数中的函数......
你可以创建一个像这样的闭包函数...
func doSomethingAsync(completion: () -> ()) { }
参数completion
的类型() -> ()
是......它是一个->
不带输入参数()
并返回void 的函数()
.
你也可以做一个像...这样的功能
// (inputs) -> (outputs) (String) -> ()
或者您想要的任何输入或输出.
现在,就像你在问题中一样.这个函数可以调用其他一些异步函数...
func myAsyncFunction(completion: () -> ()) { someOtherAsyncFunction() { // This is the completion of "someOtherAsyncFunction" // Call YOUR completion here... completion() } }
为了确保在完成其他异步方法之后调用完成,请将其置于另一个方法的完成之内.像上面一样.
现在,打电话给你,你可以做...
self.myAsyncFunction() { // your completion block code here. }
现在,在其他异步方法完成后,将调用完成块代码.
当然,如果你在另一个完成中有多个路径(比如错误等等),那么你必须在每个端点调用你的完成...
func myAsyncFunction(completion: () -> ()) { someOtherAsyncFunctionWithAPossibleError() { error in if error != nil { completion() // this return means the other completion won't be run return } completion() } }
斯威夫特4:
创建一个完成块.
func getDataFromJson(url: String, parameter: String, completion: @escaping (_ success: [String : AnyObject]) -> Void) { //@escaping...If a closure is passed as an argument to a function and it is invoked after the function returns, the closure is @escaping. var request = URLRequest(url: URL(string: url)!) request.httpMethod = "POST" let postString = parameter request.httpBody = postString.data(using: .utf8) let task = URLSession.shared.dataTask(with: request) { Data, response, error in guard let data = Data, error == nil else { // check for fundamental networking error print("error=\(error)") return } if let httpStatus = response as? HTTPURLResponse, httpStatus.statusCode != 200 { // check for http errors print("statusCode should be 200, but is \(httpStatus.statusCode)") print(response!) return } let responseString = try! JSONSerialization.jsonObject(with: data, options: .allowFragments) as! [String : AnyObject] completion(responseString) } task.resume() }
通话方式
getDataFromJson(url: "http://example.com", parameter: "vehicle_type=Car", completion: { response in print(response) })