如何在viewdidload()中使用回调函数?

时间:2019-05-01 01:43:05

标签: ios swift multithreading callback

我被赋予了一个类(客户端),该类具有一个函数(requestSitesData),该函数可以从服务器获取数据,并且其中包含@转义:

func requestSitesData(response: @escaping (_ data: Data?, _ error: Error?) -> Void) {
        DispatchQueue.global(qos: .default).asyncAfter(deadline: .now() + randomTimeDelay()) {
            guard self.isRequestSuccessful() else {
                response(nil, ClientError.requestFailed)

                return
            }
            guard let fileURL = Bundle.main.url(forResource: self.responseFilename, withExtension: "json") else {
                response(nil, ClientError.noFile)
                return 
            }
            do {
                let data = try Data(contentsOf: fileURL)
                let _ = try JSONSerialization.jsonObject(with: data)
                response(data, nil)
            } catch let error {
                response(nil, error)
            }
        }
    }

所以我认为响应函数在这里是一个回调函数。在我的项目中,我有一个全局变量来存储来自服务器的数据,并想在我的viewcontroller上显示它。但是似乎无论将call_back函数放在viewcontroller类中的什么位置,回调函数都会在所有函数之后调用(应该如此),因此我无法在viewdidload()中获取数据。

func call_back(data: Data?, error: Error?) -> Void {
        print("call_back called")
        if let file_data = data {
            if let sites_map = try? JSONSerialization.jsonObject(with: file_data, options: .mutableLeaves) as! [String: [Dictionary<String, Any>]] {
                if let sites = sites_map["sites"] {
                    for site in sites {
                        if let name = site["name"] as? String,
                        let slogan = site["slogan"] as? String,
                        let url = site["url"] as? String,
                        let description = site["description"] as? String,
                        let color = site["color"] as? String {
                            let single_site: Site = Site(name: name, slogan: slogan, url: url, description: description, color: color)
                            sites_res.append(single_site)
                        }
                    }
                }
            }
        }
    }

override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let c = Client()
        c.requestSitesData { (response_data, response_error) in
            self.call_back(data: response_data, error: response_error)
            print("ddd")
        }

    }

我不知道如何在viewdidload()中获取数据,是因为我调用此call_back函数的方式错误吗?有人可以帮忙吗?

2 个答案:

答案 0 :(得分:0)

您将需要在回调内部重新加载视图的数据,转义的闭包将使被调用的函数失效,因此,其中的回调仅在函数完成执行并将期望值返回给回调之后才会发生。

问题是您不知道返回该数据将花费多长时间,或者创建一个函数来更新以重新加载视图并让回调函数调用它,或者您可以在打开当前页面之前获取数据ViewController并将数据传递给它。

编辑1

尝试按以下所示的方式进行操作,以使其更新View Controller中的数据或仅更新View中的数据,但根据您的需要进行更改。

func call_back(data: Data?, error: Error?) -> Void {
    print("call_back called")
    if let file_data = data {
        if let sites_map = try? JSONSerialization.jsonObject(with: file_data, options: .mutableLeaves) as! [String: [Dictionary<String, Any>]] {
            if let sites = sites_map["sites"] {
                for site in sites {
                    if let name = site["name"] as? String,
                    let slogan = site["slogan"] as? String,
                    let url = site["url"] as? String,
                    let description = site["description"] as? String,
                    let color = site["color"] as? String {
                        let single_site: Site = Site(name: name, slogan: slogan, url: url, description: description, color: color)
                        sites_res.append(single_site)
                    }
                }
            }
        }
    }
}
override func viewDidLoad() {
    super.viewDidLoad()
    // Do any additional setup after loading the view, typically from a nib.
    let c = Client()
    c.requestSitesData { (response_data, response_error) in
        self.call_back(data: response_data, error: response_error)
        updateData()
    }

}

func updateData(){
//either update your data here or just update the data in the subviews.
    mylabel.text = data.text
}

答案 1 :(得分:0)

修改功能如下:

func call_back(data: Data?, error: Error?) -> [String: [Dictionary<String, Any>]]? {
            print("call_back called")
            if let file_data = data {
                if let sites_map = try? JSONSerialization.jsonObject(with: file_data, options: .mutableLeaves) as? [String: [Dictionary<String, Any>]] {
                    return sites_map
                }
            }
            return nil
        }


override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        let c = Client()
        c.requestSitesData { (response_data, response_error) in
            if let sites_map = self.call_back(data: response_data, error: response_error){
        if let sites = sites_map["sites"] {
            for site in sites {
                if let name = site["name"] as? String,
                    let slogan = site["slogan"] as? String,
                    let url = site["url"] as? String,
                    let description = site["description"] as? String,
                    let color = site["color"] as? String {
                    let single_site: Site = Site(name: name, slogan: slogan, url: url, description: description, color: color)
                    sites_res.append(single_site)
                }
            }
        }
    }
  }
}