加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

swift3 – Swift 3.0中的完成处理程序

发布时间:2020-12-14 05:45:43 所属栏目:百科 来源:网络整理
导读:我使用下面的代码与我的服务器同步数据.完成任务后,我想打电话给: self.refreshControl?.endRefreshing() 但是,我想确保它发生在此方法中可能发生的任何事情之后.这是我使用完成处理程序的地方吗?这让我感到困惑,因为我已经运行了在获得http响应后执行的代
我使用下面的代码与我的服务器同步数据.完成任务后,我想打电话给:
self.refreshControl?.endRefreshing()

但是,我想确保它发生在此方法中可能发生的任何事情之后.这是我使用完成处理程序的地方吗?这让我感到困惑,因为我已经运行了在获得http响应后执行的代码.如果我添加一个完成处理程序,它会在收到http响应后执行吗?我可以将我的endRefreshing()代码放在那里,这可能发生在下面的代码中可能发生的任何事情之后吗?
谢谢!

func syncCustomers(token: String) {
    let url:NSURL = NSURL(string: Constants.Api.BaseUrl + "api/customer")!
    let session = URLSession.shared
    let request = NSMutableURLRequest(url: url as URL)
    request.setValue("Bearer (token)",forHTTPHeaderField: "Authorization")
    request.httpMethod = "GET"
    let task = session.dataTask(with: request as URLRequest) { (data,response,error) in
        guard let data = data else { return }
        do {
            if error != nil {
                self.showAlert(title: "Error",message: error!.localizedDescription)
            }
            else if let httpResponse = response as? HTTPURLResponse {
                if httpResponse.statusCode == 200 {
                    let json = try JSONSerialization.jsonObject(with: data,options: .allowFragments) as? Array<Any>
                    DispatchQueue.global().async {
                        for item in json! {
                            if let customer = Customer(json: item as! [String : Any]) {
                                _ = SqliteDB.instance.replaceCustomer(customer: customer)
                            }
                        }
                        self.customers = SqliteDB.instance.getCustomers()
                        self.tableView.reloadData()
                    }
                } else if httpResponse.statusCode == 401 {
                    self.showAlert(title: "Error",message: "Unauthorized. Please try logging in again.")

                }
            }
        } catch let error as NSError {
            self.showAlert(title: "Error",message: error.localizedDescription)
        }
    }
    task.resume()
}
完成或闭包只是一个包含在参数中的函数……

你可以用这样的闭包来创建一个函数……

func doSomethingAsync(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()
    }

}

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读