在表视图中显示响应 api 作为 swift 中的 URL 获取的图像
Display image in tableview that are fetched in response of the api as a URL in swift
我想在 table 视图中显示来自 API 请求的图像。
我添加了从 API 获取数据的代码。但是我的图像没有显示在 table 视图中。没有错误。请帮我在 table 视图中获取图像。
**注:模板服务中的var thumbnail,是持有图片url的。
下面是我的代码:
HomeScreenViewController -
class HomeScreenViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, TemplateProtocol {
@IBOutlet weak var templateTableView: UITableView!
var imagearrayForTemplate = [String]()
var templateCount: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
templateTableView.delegate = self
templateTableView.dataSource = self
callTemplateService()
}
func callTemplateService() {
TemplateService.templateInstance.templateService(APITokenString: "API_Token_Is_passed")
TemplateService.templateInstance.delegateTemplate = self
self.templateTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TemplateService.templateInstance.templateImageArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let tableCell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell") as? TemplateTableViewCell
let imagesString = imagearrayForTemplate[indexPath.row]
tableCell?.templateImages.image = UIImage(named: imagesString)
return tableCell!
}
func template() {
let array = TemplateService.templateInstance.templateImageArray
for item in array {
self.imagearrayForTemplate.append(item)
print("Myarray \(self.imagearrayForTemplate)")
}
self.templateTableView.reloadData()
}
}
Template Service -
protocol TemplateProtocol {
func template()
}
class TemplateService {
static let templateInstance: TemplateService = TemplateService()
var templateImageArray: [String] = []
var delegateTemplate: TemplateProtocol!
func templateService(APITokenString: String) {
let url = URL(string: "Have added API_URL to get the response")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("Bearer "+APITokenString, forHTTPHeaderField: "Authorization")
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let httpResponse = response as? HTTPURLResponse {
print("statusCode: \(httpResponse.statusCode)")
print(httpResponse)
}
if let data = data {
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { return }
print(json)
let template = TemplateData(json: json)
let templateData = template.data
for items in templateData {
print(items)
for (key,value) in items
{
if key == "thumbnail"{
print(value)
self.templateImageArray.append(value as! String)
}
}
}
DispatchQueue.main.async {
self.delegateTemplate.template()
}
}catch {
print(error)
}
}
}.resume()
}
}
TemplateTableViewCell -
class TemplateTableViewCell: UITableViewCell {
@IBOutlet weak var templateImages: UIImageView!
func configure(url: String) {
templateImages.image = UIImage(named: url)
}
}
UIImage(named: String) 尝试在本地加载图片,
您需要下载图像。
为此,请考虑使用 kingfisher 之类的图片下载器:
imageView.kf.setImage(with: url)
我想在 table 视图中显示来自 API 请求的图像。 我添加了从 API 获取数据的代码。但是我的图像没有显示在 table 视图中。没有错误。请帮我在 table 视图中获取图像。
**注:模板服务中的var thumbnail,是持有图片url的。
下面是我的代码:
HomeScreenViewController -
class HomeScreenViewController: UIViewController,UITableViewDelegate, UITableViewDataSource, TemplateProtocol {
@IBOutlet weak var templateTableView: UITableView!
var imagearrayForTemplate = [String]()
var templateCount: Int = 0
override func viewDidLoad() {
super.viewDidLoad()
templateTableView.delegate = self
templateTableView.dataSource = self
callTemplateService()
}
func callTemplateService() {
TemplateService.templateInstance.templateService(APITokenString: "API_Token_Is_passed")
TemplateService.templateInstance.delegateTemplate = self
self.templateTableView.reloadData()
}
func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
return TemplateService.templateInstance.templateImageArray.count
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let tableCell = tableView.dequeueReusableCell(withIdentifier: "tableViewCell") as? TemplateTableViewCell
let imagesString = imagearrayForTemplate[indexPath.row]
tableCell?.templateImages.image = UIImage(named: imagesString)
return tableCell!
}
func template() {
let array = TemplateService.templateInstance.templateImageArray
for item in array {
self.imagearrayForTemplate.append(item)
print("Myarray \(self.imagearrayForTemplate)")
}
self.templateTableView.reloadData()
}
}
Template Service -
protocol TemplateProtocol {
func template()
}
class TemplateService {
static let templateInstance: TemplateService = TemplateService()
var templateImageArray: [String] = []
var delegateTemplate: TemplateProtocol!
func templateService(APITokenString: String) {
let url = URL(string: "Have added API_URL to get the response")
var request = URLRequest(url: url!)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Content-Type")
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue("Bearer "+APITokenString, forHTTPHeaderField: "Authorization")
let session = URLSession.shared
session.dataTask(with: request) { (data, response, error) in
if let httpResponse = response as? HTTPURLResponse {
print("statusCode: \(httpResponse.statusCode)")
print(httpResponse)
}
if let data = data {
do {
guard let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String: Any] else { return }
print(json)
let template = TemplateData(json: json)
let templateData = template.data
for items in templateData {
print(items)
for (key,value) in items
{
if key == "thumbnail"{
print(value)
self.templateImageArray.append(value as! String)
}
}
}
DispatchQueue.main.async {
self.delegateTemplate.template()
}
}catch {
print(error)
}
}
}.resume()
}
}
TemplateTableViewCell -
class TemplateTableViewCell: UITableViewCell {
@IBOutlet weak var templateImages: UIImageView!
func configure(url: String) {
templateImages.image = UIImage(named: url)
}
}
UIImage(named: String) 尝试在本地加载图片, 您需要下载图像。 为此,请考虑使用 kingfisher 之类的图片下载器:
imageView.kf.setImage(with: url)