【发布时间】:2018-01-19 13:36:11
【问题描述】:
我得到了一个带有 url 参数的 getJSON 函数:
func getJsons(jsonUrl: String) {
guard let url = URL(string: jsonUrl) else { return }
URLSession.shared.dataTask(with: url:) { (data, response, err) in
if err != nil {
print("ERROR: \(err!.localizedDescription)")
let alertController = UIAlertController(title: "Error", message:
err!.localizedDescription, preferredStyle: UIAlertControllerStyle.alert)
alertController.addAction(UIAlertAction(title: "Dismiss", style: UIAlertActionStyle.default,handler: nil))
var topController:UIViewController = UIApplication.shared.keyWindow!.rootViewController!
while ((topController.presentedViewController) != nil) {
topController = topController.presentedViewController!;
}
topController.present(alertController, animated: true, completion: nil)
}
guard let data = data else { return }
do {
let test = try JSONDecoder().decode([ArticleStruct].self, from: data)
DispatchQueue.main.async {
self.myArticles = test
print(self.myArticles?.count ?? 0 )
self.myTableView.reloadData()
}
} catch let jsonErr {
print("Error:", jsonErr)
}
}.resume()
}
现在我想将函数移动到另一个类(网络类)。
我必须做什么才能将completionHandler 添加到函数中,以及如何从其他类中调用它。 我想将 json 返回给调用者类。
我的计划:
在MainActivity -> viewDidLoad:调用网络completionHandler(getJsons(192.168.178.100/getPicture.php)) 完成时-> myJsonDataMainActivity =(来自completionHandler的json数据) -> MainActivity.TableView.reload
在 otherClass -> 调用网络completionHandler(getJsons(192.168.178.100/getData.php)) 完成时-> myJsonDataOtherClass =(来自completionHandler的json数据) -> otherClass.TableView.reload
感谢您的帮助!
【问题讨论】: