ios - 如何使用 Google API 从 Internet 获取图像并将第一个结果插入 UIImageView
问题描述
我有一个带有产品的 UITableView,每个产品都有一个 UIImageView,应该使用谷歌 API 从谷歌填充。因此,如果我的产品名称是“iPhone X”,那么我的 UIImageView 应该填充来自 google 的第一个图像结果,这将是一个带有 iPhone X 的图像。有时会为我获取第一个产品的图像以及 UITableView 的所有产品将有相同的图像,但 90% 的时间是让我得到默认图像,即带有狗的图像。
这是我的代码:
class ProductsViewController: UIViewController{
var query: String?
var googlePhotosArray = [Item]()
var productsArray = [Product]()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
fetchPhotosForProductsFromGoogle()
}
// Download photos from Google for products avatar
func fetchPhotosForProductsFromGoogle(){
for eachProduct in productsArray{
let productNameWithSpaces = eachProduct.name!
query = productNameWithSpaces.replacingOccurrences(of: " ", with: "_", options: .literal, range: nil)
}
guard let requestURL = URL(string: URLGoogle.googleAPIUrl + "\(query ?? "ChihuahuaExtreme")" + URLGoogle.googleSearchPhotosOnly + URLGoogle.googleSearchEngineID + URLGoogle.googleAPIKey)
else { fatalError(Constants.urlNotFound) }
URLSession.shared.dataTask(with: requestURL) { (data, response, error) in
guard error == nil else {
DispatchQueue.main.async { SCLAlertView().showError(Constants.error, subTitle: Constants.errorURLSesion) }
return
}
do {
let googlePhotosList = try JSONDecoder().decode(GoogleSearchModel.self, from: data!)
self.googlePhotosArray = self.googlePhotosArray + googlePhotosList.items
} catch { }
DispatchQueue.main.async {
self.productsTableView.reloadData()
}
}.resume()
}
}
func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
let cell = productsTableView.dequeueReusableCell(withIdentifier: Constants.identifierProductCell, for: indexPath) as! ProductTableViewCell
cell.delegate = self
cell.productTitleLabel.text = productsArray[indexPath.row].name!
cell.productDescriptionLabel.text = productsArray[indexPath.row].prodDescription!
cell.productPriceLabel.text = String(format: Constants.floatTwoDecimals, productsArray[indexPath.row].price) + Constants.currencyPound
DispatchQueue.main.async {
let productPhotoURL = self.googlePhotosArray.first?.link ?? Constants.defaultProductPhotoURL
let resourcePhoto = ImageResource(downloadURL: URL(string: productPhotoURL)!, cacheKey: productPhotoURL)
cell.productImageView.kf.setImage(with: resourcePhoto)
}
// Customize AddToCart btn
cell.addToCartBtn.layer.cornerRadius = 8
cell.addToCartBtn.layer.borderWidth = 2
cell.addToCartBtn.layer.borderColor = UIColor.white.cgColor
return cell
}
// Set URL Google
extension URLGoogle{
static let googleAPIUrl = "https://www.googleapis.com/customsearch/v1?q="
static let googleSearchPhotosOnly = "&imgType=photo&imgSize=medium&searchType=image"
static let googleSearchEngineID = "&cx=004797504301667307438:v974oybby28"
static let googleAPIKey = "&key=AIzaSyA_QlOnYMZLbFCV_oh49Z97_tx7zA-Qeig"
}
这是错误:
这是我的项目的源代码,可能比这个示例更能帮助你:https ://bitbucket.org/florentin89/shoppingland/src/c0d06b7d5a307ca8ee6f4ab6f962e81f2afbd0d5/ShoppingLand/Controller/ProductsViewController.swift?at=master&fileviewer=file-view-默认
如果您需要更多信息,请随时问我。
如果您正在阅读本文,非常感谢您抽出宝贵的时间!
解决方案
替换ChihuahuaExtreme
为名称textField
中的内容requestURL
推荐阅读
- r - 接收器仅通过控制台而不是通过源保存数组
- wordpress - Woocommerce 更改购物车图标
- python - 从页面源python获取特定部分
- sql-server - 为什么高可用性组会抛出错误 35250?
- javascript - 评估字符串中的数学运算符以与随机数一起使用
- jquery - 使用 jQuery 的悬停问题
- excel - VBA中的转义字符
- c++ - Visual C++ (VS2017) 中的模糊用户定义转换
- python - SQLAlchemy 不可为空 ForeignKey 约束违反
- jakarta-ee - Wildfly 初始化:时间延迟导致 Java-EE 应用程序中的 IllegalStateException