首页 > 解决方案 > 如何使用 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-默认

如果您需要更多信息,请随时问我。

如果您正在阅读本文,非常感谢您抽出宝贵的时间!

标签: iosswiftswift4nsfetchedresultscontroller

解决方案


替换ChihuahuaExtreme为名称textField 中的内容requestURL


推荐阅读