我正在使用如果在swift的前一阶段循环,但在更新版本中我无法使用相同的循环。我试过使用后卫,但它也没有工作。
let imageArray = dataObject?["image"] as! NSArray
if let image = imageArray[0]{
let imageURL = "compute.amazonaws.com/" + "\(image)"
print(imageURL)
if let url: URL = URL(string:"\(imageURL)")!{
let task = URLSession.shared.dataTask(with: url, completionHandler: { (responseData, responseUrl, error) -> Void in
if let data = responseData{
DispatchQueue.main.async(execute: { () -> Void in
cell?.imageViewProduct.image = UIImage(data: data)
})
}
})
task.resume()
}
}
这里我的图像,即imageArray [0]是可选值。在某些情况下它可能不会从后端提供,所以我想使用if或类似的东西。
答案 0 :(得分:0)
我不确定,你的问题是什么,但我宁愿这样做:
guard let imageArray = dataObject?["image"] as? [String] else {return} //as I understand, names of images here
guard let image = imageArray.firstObject else {return}
let imageURL = "compute.amazonaws.com/\(image)"
print(imageURL)
if let url = URL(string:"\(imageURL)") {
let task = URLSession.shared.dataTask(with: url, completionHandler: { (responseData, responseUrl, error) -> Void in
if let data = responseData{
DispatchQueue.main.async(execute: { () -> Void in
cell?.imageViewProduct.image = UIImage(data: data)
})
}
})
task.resume()
}
稍微修改了我的代码。你不需要分开那个字符串
答案 1 :(得分:0)
试试这个:
let imageArray = dataObject?["image"] as! NSArray
if let image = "\(imageArray[0])" as? String{
let imageURL = "compute.amazonaws.com/" + "\(image)"
print(imageURL)
if let url: URL = URL(string:"\(imageURL)")!{
let task = URLSession.shared.dataTask(with: url, completionHandler: { (responseData, responseUrl, error) -> Void in
if let data = responseData{
DispatchQueue.main.async(execute: { () -> Void in
cell?.imageViewProduct.image = UIImage(data: data)
})
}
})
task.resume()
}
}