unable to print response from api in collectionView

Viewed 69

I have post request type API I use the request.HTTP method = "POST" to hit API

here's my code is

var posts = [[String: Any]]()

func apicall() {
    let Url = String(format: "http://example.com")
    guard let serviceUrl = URL(string: Url) else { return }
    
    var request = URLRequest(url: serviceUrl)
    request.httpMethod = "POST"
    request.setValue("Application/json", forHTTPHeaderField: "Content-Type")
    
    let session = URLSession.shared
    session.dataTask(with: request) { (data, response, error) in
        if let response = response {
            print(response)
        }
        if let data = data {
           do {
                if let json = try JSONSerialization.jsonObject(with: data, options: []) as? [String : Any] {
                    self.posts = json["data"] as! [[String : Any]]
                    print("here the data that i want \(self.posts)")
                }
            } catch {
                print(error)
            }
        }
    }.resume()
}

now I get the response in JSON and print. now I don't know how to print the JSON in collectionView

here's my collectionView code

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

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "Cell", for: indexPath) as! CreatGroupCollectionViewCell
    let link = "http://example.com" + posts[indexPath.row]["icons"] as! String
    cell.lbl.text = posts[indexPath.row]["name"] as? String
    cell.btn2.downloaded(from: link)
    return cell
}

I'm unable to print image on the button and I use extension for this

1 Answers

you just need to reload you collectionView - try this in your do statement

DispatchQueue.main.async() {
   self.collectionView.reloadData()
       }
Related