我有这个代码可以显示来自URLS的图像。我认为一切都很好,因为当我打印图像的数量和images
时,我得到了7个图像的数组。
请查看我的代码并纠正我错误的地方。
import UIKit
import SwiftyJSON
import Haneke
class SlideViewController: UIViewController , UITableViewDelegate , UITableViewDataSource {
@IBOutlet weak var tableview : UITableView!
var images = [String]()
override func viewDidLoad() {
super.viewDidLoad()
tableview.delegate = self
tableview.dataSource = self
getJSON()
}
func numberOfSections(in tableView: UITableView) -> Int {
return 0
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return images.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "imageCell", for: indexPath) as! ImageTableViewCell
let remote = images[indexPath.row]
let imageurl = URL(string: remote)
cell.images.sd_setImage(with: imageurl)
return cell
}
func getJSON() {
let url = "http://localhost:8000/api/hello"
let myuel = URL(string: url)
let resquest = NSMutableURLRequest(url: myuel!)
resquest.httpMethod = "GET"
let task = URLSession.shared.dataTask(with: resquest as URLRequest, completionHandler: { data,response,error in
if error != nil{
print(error!.localizedDescription)
return
}
let json = JSON(data)
self.images = json["pic"].arrayObject! as! [String]
print(self.images.count)
print(self.images)
DispatchQueue.main.async {
self.tableview.reloadData()
}
})
task.resume()
}
}
答案 0 :(得分:0)
确保从以下方法返回一个部分
func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
使用此扩展程序以异步方式加载和查看来自网址的图片
extension UIImageView {
public func imageFromServerURL(urlString: String) {
URLSession.shared.dataTask(with: NSURL(string: urlString)! as URL, completionHandler: { (data, response, error) -> Void in
if error != nil {
print(error)
return
}
DispatchQueue.main.async(execute: { () -> Void in
let image = UIImage(data: data!)
self.image = image
})
}).resume()
}}
使用上面的扩展程序将图片加载到imageView,就像这样。
cell.imageview.imageFromServerURL(urlString: urlString)