在我的项目中,我展示了一个 UITableView
,其中当前包含描述从远程 JSON 文件加载的节目名称和类型的文本。
这一切都有效。接下来我想要的是使用 JSON 文件中的 URL 并加载每个节目旁边的缩略图。
使用教程,我添加了一个功能来下载带有打印的远程图像以测试是否成功。
if let shows_list = json as? NSArray
{
for i in 0 ..< data_list.count
{
if let shows_obj = shows_list[i] as? NSDictionary
{
let show_name = shows_obj["show"] as? String
let show_genre = shows_obj["genre"] as? String
let show_image = shows_obj["thumbnail"] as? String
TableData.append(show_name! + " | " + show_genre!)
let testPictureURL = URL(string: show_image!)!
let session = URLSession(configuration: .default)
// Here's the download task where I'm grabbing the image
let downloadPicTask = session.dataTask(with: testPictureURL) { (data, response, error) in
// The download has finished.
if let e = error {
print("Error downloading cat picture: \(e)")
} else {
// No errors found.
if let res = response as? HTTPURLResponse {
print("Downloaded picture with response code \(res.statusCode)")
if let imageData = data {
// Now I know I have data, so I think I can use UIImage to convert it into an image
let image = UIImage(data: imageData)
} else {
print("Couldn't get image: Image is nil")
}
} else {
print("Couldn't get response code for some reason")
}
}
}
downloadPicTask.resume()
}
JSON 数组中有三个项目,我得到三个打印语句,表明图片已下载:但图像没有出现。
我的理论:因为这是一个表格,也许我必须将其添加为附件,但没有图像附件子类。
我是 Swift 新手 - 您对我应该如何将此上传的图像附加到表中有什么想法吗?
最佳答案
这可能是由 URLSession
的异步行为引起的,因此当请求的图像返回时, View 已经加载。
要解决这个问题,您可以使用回调,例如:
func myFunction(completion: (returnedImage -> UIIMage) -> Void){
//...
let downloadPicTask = session.dataTask(with: testPictureURL) { (data, response, error) in
//...
let image = UIImage(data: imageData)
completion(returnedImage: image)
//...
}
downloadPicTask.resume()
}
}
通过使用回调,假设您有一个名为 myFunction(completion:)
的方法,因此现在当您调用该方法时,您可以处理从 completion
返回的任何内容>:
myFunction { (image) in
DispatchQueue.main.async { cell.imageView.image = image }
}
关于ios - 在 Swift 3 中的 UITableView 中添加图像作为附件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48363439/