我正在尝试快速从我的数据库中提取图像。我可以检索价格、视频和 p_name,但不能检索图像。我想UIImageView
用数据库中的图像更新 updateImage,但出现两个错误。
错误一说:
类型“ViewController.Class”不符合协议“Encodable”
错误二说:
类型“ViewController.Class”不符合协议“Dec”
有什么好的解决方法?
这是JSON:
{
"id":"1",
"p_name":"item_one",
"image":"item_one.png"
}
{
"id":"2","p_name":
"item_two","image":
"item_two.img"
}
还有快速代码:
import UIKit
class ViewController: UIViewController {
@IBOutlet weak var updateLabel: UILabel!
@IBOutlet weak var updateImage: UILabel!
struct Class: Codable
{
let id: String
let p_name: String
let image: String
}
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view, typically from a nib.
let url = URL(string: "http://host-2:8888//getClasses.php")
// Load the URL
URLSession.shared.dataTask(with: url!, completionHandler: {(data, response, error) in
// If there are any errors don't try to parse it, show the error
guard let data = data, error == nil else { print(error!); return }
let decoder = JSONDecoder()
let classes = try! decoder.decode([Class].self, from: data)
// Print out the classes to the console - try sticking this in a table view :)
for myClass in classes {
self.updateLabel.text = myClass.p_name
self.updateImage.text = myClass.image
}
}).resume()
}
}