我想用url下载图像并将图像指定为表格视图单元格图像。当从服务器获取url然后调用下载的下载图像方法图像,但对于没有图像的项目,我应该在我的图像数组中添加默认图像,我将图像追加到图像数据阵列时出现问题,默认图像首先附加然后下载图像追加,我的表视图数据不正确。有我的代码,有关如何等待追加下载图像,然后添加默认图像的任何想法?
func getVitrinList() {
let param = ["userid":"6","key":"so@gYFDS#","action":"vitrin","step":"list","sort":self.sortType,"filter":self.filterID,"start":"","end":""]
let url = "http//***.php"
sendRequest.pair = param
sendRequest.stringForUrl = url
sendRequest.fetchRequest() {
(JSONResult) -> Void in
switch JSONResult {
case let .success(response):
OperationQueue.main.addOperation({
if ((response.error as? Int) == 0) {
let arrJSON = response.result as! Array<Any>
for index in 0...(arrJSON.count-1) {
let aObject = arrJSON[index] as! [String : AnyObject]
if let imageURL = aObject["image"] as? String {
let checkedUrl = URL(string: imageURL)
self.downloadImage(url: checkedUrl)
}
}
}
}
}
})
case let .failure(error):
print("Error fetching recent post \(error)")
}
}
}
func getDataFromUrl(url: URL, completion: @escaping (_ data: Data?, _ response: URLResponse?, _ error: Error?) -> Void) {
URLSession.shared.dataTask(with: url) { (data, response, error) in
guard let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
let data = data, error == nil,
let image = UIImage(data: data)
else { return }
DispatchQueue.main.async() { () -> Void in
self.imageData.append(image)
}
}.resume()
}
func downloadImage(url: URL?) {
OperationQueue.main.addOperation () {
if url != nil {
self.getDataFromUrl(url: url!) { (data, response, error) in
print("all image download")
}
}
else {
DispatchQueue.main.async {
self.imageData.append(#imageLiteral(resourceName: "offeshLogo"))
self.HomeTabel.reloadData()
}
}
if self.imageData.count == 0 {
self.descriptView.isHidden = true
}
}
}