class FirstViewController: TFBaseViewController { var ljload :LJDownLoadNetimage? //声明 override func viewDidLoad() { super.viewDidLoad() self.view.backgroundColor = UIColor.white self.setTopNavBarTitle("首页") ljload = LJDownLoadNetimage() self.inittest() }
//MARK: 点击事件 func buttonClick(_ sender:UIButton) { //避免循环引用,weak当对象销毁的时候,对象会被指定为nil //weak var weakSelf = self //对象推到,省略了ViewController weak var weakSelf : FirstViewController? = self //等同与上面的表达式 //数据回调 ljload?.loadData({ (jsonData:String) in print("获取到的数据:\(jsonData)") weakSelf?.view.backgroundColor = UIColor.red }) //let vc = TFNetimageViewController() //self.navigationController?.pushViewController(vc,animated: true) }
import Foundation class LJDownLoadNetimage: NSObject { //闭包类型 (参数列表)->(返回值类型) func loadData(_ finishCallBack: @escaping (_ jsonData:String) -> ()) { //1. 发送异步网络请求 //放在此处,可以不加@escaping // finishCallBack() if #available(iOS 8.0,*) { dispatchQueue.global().async { print("发送异步网络请求") dispatchQueue.main.async(execute: { //放在此处必须要加@escaping finishCallBack("jsonData") }) } } } }
控制台打印的数据
发送异步网络请求
获取到的数据:jsonData