【发布时间】:2019-04-20 14:14:29
【问题描述】:
我想将图像从 api 加载到单元格内的 UIImageView 中。但是由于我首先连续两次收到 nill 值,所以我无法做到。 这是我的代码:
class MainController: UITableViewController{
var nulti = [Nulti]()
var picture = Picture()
let urlDel = "http://xx"
let urlPic = "http://xxx/"
override func viewDidLoad() {
super.viewDidLoad()
self.tableView.rowHeight = 44
getNulti()
}
func getNulti(){
Alamofire.request(urlDel, method: .get)
.responseJSON { (response) in
if response.result.isSuccess {
guard let responseData = response.data else {return}
let jsonDecoder = JSONDecoder()
self.nulti = try! jsonDecoder.decode([Nulti].self, from: responseData)
for pic in self.nulti{
let id = pic.image
if(id != nil){
self.getPicture(id: id!.description)
}
}
self.tableView.reloadData()
}
else {
print("Error: \(String(describing: response.result.error))")
}
}
}
func getPicture(id: String){
Alamofire.request(urlPic + id, method: .get)
.responseJSON { response in
if response.result.isSuccess {
guard let responseData = response.data else {return}
let jsonDecoder = JSONDecoder()
self.picture = try! jsonDecoder.decode(Picture.self, from: responseData)
self.tableView.reloadData()
} else {
print("Error: \(String(describing: response.result.error))")
}
}
}
func picConvertor(id : String) -> UIImage{
let dataDecoded : Data = Data(base64Encoded: id, options: .ignoreUnknownCharacters)!
let decodedimage = UIImage(data: dataDecoded)
return decodedimage!
}
override func numberOfSections(in tableView: UITableView) -> Int {
return 1
}
override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return nulti.count
}
override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = tableView.dequeueReusableCell(withIdentifier: "Cell", for: indexPath) as! Cell//
cell.cell?.text = nulti[indexPath.row].name
print(self.picture)
//let id = self.picture.image!.description
//cell.logo?.image = picConvertor(id: id)
return cell
}
}
然后我做了 print(self.picture) 看看发生了什么,然后我看到了这个
图片(id:nil,格式:nil,图片:nil)
图片(id:nil,格式:nil,图片:nil)
图片(id: Optional(2), format: Optional("png"), image: Optional("iVBORw0KGgoAAA...")
图片(id: Optional(2), format: Optional("png"), image: Optional("iVBORw0KGg...")
【问题讨论】: