大家好,代码如下
struct NetworkImageManager {
func fetchCurrentImage(completionHandler: @escaping (CurrrenImage)-> Void) {
let urlString = "https://pixabay.com/api/?key=\(key)&q&image_type=photo"
guard let url = URL(string: urlString) else {return}
let urlSession = URLSession(configuration: .default)
let task = urlSession.dataTask(with: url) { data, responce, error in
if let data = data {
if let currentImage = self.parseJSON(withData: data){
completionHandler(currentImage)
}
}
}
task.resume()
}
func parseJSON(withData data: Data) -> CurrrenImage? {
let decoder = JSONDecoder()
do {
let currentImageData = try decoder.decode(CurrentImageData.self, from: data)
guard let currentImage = CurrrenImage(currentImageData: currentImageData) else {return nil
}
return currentImage
} catch let error as NSError {
print(error)
}
return nil
}
}
尝试将数据从一个视图传输到另一个视图时,会产生以下错误(该错误在 // 之后描述)
class CollectionViewController: UICollectionViewController {
let itemsPerRow: CGFloat = 2
let sectionInserts = UIEdgeInsets(top: 20, left: 20, bottom: 20, right: 20)
let networkImageManager = NetworkImageManager()
override func viewDidLoad() {
super.viewDidLoad()
networkImageManager.fetchCurrentImage(completionHandler: CurrrenImage) // Cannot convert value of type 'CurrrenImage.Type' to expected argument type '(CurrrenImage) -> Void'
}
该错误表示该类型作为参数传递。
要得到结果:
考虑到闭包是一个普通函数,只是没有名字,所以它
completionHandler
写成 notCurrrenImage
,但是: