Search code examples
iosjsonswiftsdwebimage

Swift: Error while Parsing JSON data from alamofire into array with Dictionary


I have the below JSON response and i want to get the id and url.

[
  {
    "albumId": 1,
    "id": 1,
    "title": "accusamus beatae ad facilis cum similique qui sunt",
    "url": "https://via.placeholder.com/600/92c952",
    "thumbnailUrl": "https://via.placeholder.com/150/92c952"
  }]

And in view controller I have coding as following.

import UIKit
import Alamofire
import SDWebImage


class AlbumResponse: Codable {
    var list: Int
    var hits: [Album]
}


class Album: Codable {
    var id: Int
    var title : String
    var url: String
    var thumbnailUrl : String
}



class CollectionView: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout {

    let url1 = ["JSON URL"]
    @IBOutlet weak var collection: UICollectionView!
    var arrList = [Album]()


    override func viewDidLoad() {
        super.viewDidLoad()
        reequest()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(true)
        self.collection.reloadData()

    }

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        return arrList.count

    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

        let cell: firstCollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! firstCollectionViewCell
        let objct = arrList[indexPath.row]
        cell.label.text =  String(objct.id)
        cell.img!.sd_setImage(with: URL(string: objct.url), placeholderImage: #imageLiteral(resourceName: "download"), options: .retryFailed, completed: nil)

        return cell
    }

    func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {

        let width = (self.view.frame.size.width - 5 * 2 ) / 2 //some width
        let height = width * 1.45 //ratio
        return CGSize(width: width, height: height)
    }


    func reequest() {

        let url = URL(string: "JSON URL")
        Alamofire.request(url!).responseJSON {(response) in

            switch (response.result){
            case .success:
                if let data = response.data {
                    do {
                        let response = try JSONDecoder().decode(AlbumResponse.self, from: data)
                        self.arrList = response.hits
                        DispatchQueue.main.async {
                        self.collection.reloadData()
                        }
                    } catch {
                        print(error.localizedDescription)
                    }
                }

            case .failure(let error):
                print("error to print the data \(error)")
            }
        }

    }
}

When I run it's showing black screen


Solution

  • I tried and I just find the correct way. Here is the correct code.

    import UIKit
    import Alamofire
    import SDWebImage
    
    
    class Album: Codable {
        var url : String
        var id : Int
    }
    
    
    class ViewController: UIViewController,UICollectionViewDelegate,UICollectionViewDataSource {
    
        @IBOutlet weak var collection: UICollectionView!
        var urls = URL(string: "my Url")
    
        var arrList = [Album]()
    
        override func viewDidLoad() {
            super.viewDidLoad()
            request()
        }
    
        func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
            return arrList.count
        }
    
        func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
            let cell : CollectionViewCell = collectionView.dequeueReusableCell(withReuseIdentifier: "cell", for: indexPath) as! CollectionViewCell
    
                let obj = arrList[indexPath.row]
            cell.label.text = String(obj.id)
            cell.imageview!.sd_setImage(with: URL(string: obj.url), placeholderImage: #imageLiteral(resourceName: "6-things-main"), options: .cacheMemoryOnly, completed: nil)
            return cell
        }
    
    
        func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize {
    
        let width = (self.view.frame.size.width - 1 * 2 ) / 2
        let height = width * 1.45
            return CGSize(width: width, height: height)
        }
    
        func request() {
    
            let url = URL(string: "my url")
            Alamofire.request(url!).responseJSON {(response) in
    
                switch (response.result) {
                case .success:
                    if let data = response.data {
                        do {
                            let response = try JSONDecoder().decode([Album].self, from: data)
                            self.arrList = response
                            DispatchQueue.main.async {
                                self.collection.reloadData()
                            }
                        } catch {
                            print(error.localizedDescription)
                        }
                    }
                case .failure( let error):
                    print(error)
                }
            }
        }
    }
    

    Comment if you have still face any issues.