图像未显示在collectionView中

问题描述 投票:0回答:5

当我运行此代码时,它在我的collectionView中没有显示任何内容。我的代码 -

   class ViewController: UIViewController, UICollectionViewDelegate, UICollectionViewDataSource {

        @IBOutlet weak var collectionView: UICollectionView!
        var AllImage: [String] = []
          var boolValue = false

        override func viewDidLoad() {
            super.viewDidLoad()

            collectionView.delegate = self
            collectionView.dataSource = self

            downloadJson()
        }

        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            print("Found - \(AllImage.count)")
            return AllImage.count
        }

        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell:CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CollectionViewCell
            cell.myImage.image = UIImage(named: AllImage[indexPath.row])
            return cell

        }

        //MARK: Image
        func downloadJson(){
            var access_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEwMjc2LCJpc3MiOiJodHRwczovL2hvbWlpdGVzdC5jby56YS9hcGkvbG9naW4iLCJpYXQiOjE1NTIxOTYwMjIsImV4cCI6MTU1NDc4ODAyMiwibmJmIjoxNTUyMTk2MDIyLCJqdGkiOiJBeTY5R0JkZDA5dWdFTDBhIn0.czpQQsC08vuTB8iGdTeEjjQUmzl6I5Cs0VQ8WeA5VaY"
            let headers = ["Authorization": "Bearer "+access_token+"", "Content-Type": "application/json"]
            Alamofire.request("https://homiitest.co.za/api/gallery", method: .get,  parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
                if response.result.isSuccess{
                    print(response)

                    let swiftyJson = JSON(response.data!)

                    let productTemplate = swiftyJson["data"].array
                    print("hello there - \(productTemplate)")

                    for product in productTemplate! {

                        if let data = product["data"].bool {
                            continue
                        } else
                        {
                            print("I am in this block")
                            self.AllImage.append(product.stringValue)

                        }
                        self.collectionView!.reloadData()
                    }

                }

            }

        }
    }

回应 - enter image description here

ios swift uicollectionview alamofire
5个回答
1
投票

只需添加此功能

func NKPlaceholderImage(image:UIImage?, imageView:UIImageView?,imgUrl:String,compate:@escaping (UIImage?) -> Void){

    if image != nil && imageView != nil {
        imageView!.image = image!
    }

    var urlcatch = imgUrl.replacingOccurrences(of: "/", with: "#")
    let documentpath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0]
    urlcatch = documentpath + "/" + "\(urlcatch)"

    let image = UIImage(contentsOfFile:urlcatch)
    if image != nil && imageView != nil
    {
        imageView!.image = image!
        compate(image)

    }else{

        if let url = URL(string: imgUrl){

            DispatchQueue.global(qos: .background).async {
                () -> Void in
                let imgdata = NSData(contentsOf: url)
                DispatchQueue.main.async {
                    () -> Void in
                    imgdata?.write(toFile: urlcatch, atomically: true)
                    let image = UIImage(contentsOfFile:urlcatch)
                    compate(image)
                    if image != nil  {
                        if imageView != nil  {
                            imageView!.image = image!
                        }
                    }
                }
            }
        }
    }
}

只是替换

cell.myImage.image = UIImage(named: AllImage[indexPath.row])

// Here imgPicture = your imageView
// UIImage(named: "placeholder") is Display image brfore download and load actual image. 

NKPlaceholderImage(image: UIImage(named: "placeholder"), imageView: cell.myImage, imgUrl: AllImage[indexPath.row]) { (image) in }

这是你的第一个数组图像。

enter image description here


1
投票

UIImage(named:String)从资产目录中加载图像。由于AllImage包含图像网址,因此您需要先显示每个图像,然后才能显示它们。我建议使用一个库(Kingfisher是一个很棒的,很容易使用)。您需要替换此行代码

cell.myImage.image = UIImage(named: AllImage[indexPath.row])

let url = URL(string: AllImage[indexPath.row])
cell.myImage.kf.setImage(with: url)

1
投票

请格式化您的下载代码,而不是将URL字符串保存到数组中以正确加载图像。我已经更新了代码。请参考下文。

//MARK: Image
    func downloadJson(){
        let access_token = "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJzdWIiOjEwMjc2LCJpc3MiOiJodHRwczovL2hvbWlpdGVzdC5jby56YS9hcGkvbG9naW4iLCJpYXQiOjE1NTIxOTYwMjIsImV4cCI6MTU1NDc4ODAyMiwibmJmIjoxNTUyMTk2MDIyLCJqdGkiOiJBeTY5R0JkZDA5dWdFTDBhIn0.czpQQsC08vuTB8iGdTeEjjQUmzl6I5Cs0VQ8WeA5VaY"
        let headers = ["Authorization": "Bearer "+access_token+"", "Content-Type": "application/json"]
        Alamofire.request("https://homiitest.co.za/api/gallery", method: .get,  parameters: nil, encoding: JSONEncoding.default, headers: headers).responseJSON { response in
            if response.result.isSuccess{
                //print(response)

                let swiftyJson = JSON(response.data!)

                let productTemplate = swiftyJson["data"].array
                //print("hello there - \(productTemplate)")

                for product in productTemplate! {
                    // print(product["image_medium"].stringValue)
                    self.AllImage.append(product.stringValue)
                    print("this is data - \(product.stringValue)")
                }
                self.collectionView!.reloadData()

            }

        }

    }

0
投票

如果您不想安装pod,请尝试此操作。让imageCache = NSCache()

extension UIImageView {

    func imageFromServerURL(_ URLString: String, placeHolder: UIImage?) {

        self.image = nil
        if let cachedImage = imageCache.object(forKey: NSString(string: URLString)) {
            self.image = cachedImage
            return
        }

        self.image = placeHolder

        if let url = URL(string: URLString) {
            URLSession.shared.dataTask(with: url, completionHandler: { (data, response, error) in
                if error != nil {
                    print("ERROR LOADING IMAGES FROM URL: \(String(describing: error))")
                    return
                }
                DispatchQueue.main.async {
                    if let data = data {
                        if let downloadedImage = UIImage(data: data) {
                            imageCache.setObject(downloadedImage, forKey: NSString(string: URLString))
                            self.image = downloadedImage
                        }
                    }
                }
            }).resume()
        }
    }
}

使用 :

cell.myImage.imageFromServerURL(AllImage[indexPath.row], placeHolder:PLACEHOLDER_IMAGE)

如果您有任何疑问,请告诉我。


0
投票

如果你不想使用其他图书馆,如qazxsw poi,qazxsw poi,qazxsw poi等,你仍然可以使用Alamofire。

AlamofireImage

你可以像这样使用它:

AFNetworking
© www.soinside.com 2019 - 2024. All rights reserved.