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") }) } } } }
控制台打印的数据
@H_404_19@发送异步网络请求
原文链接:https://www.f2er.com/swift/321494.html