Mayowa Paul
Mayowa Paul

Reputation: 65

Image not show in table view cell

strong textI am trying to download images from the Unsplash API into a table view but for some reason its not showing in the table view cell. According to the documentation, downloading an image should look like this "photo.urls.raw" Below is the logic for downloading images. How do I resolve this ?

link: https://github.com/lexypaul13/Photo-Finder

   **Data Model:**
    struct Photos: Codable {
        var id: String?
        var createdAt: String?
        var updatedAt: String?
        var promotedAt: String?
        var width: Int?
        var height: Int?
        var color: String?
        var blurHash: String?
        var photoDescription: String?
        var altDescription: String?
        var urls: Urls?
        var likes: Int?
        var likedByUser: Bool?
        var user: User?
    
    }
    
    // MARK: - User
    struct User:Codable {
        var id: String?
        var updatedAt: String?
        var username: String?
        var name: String?
        var firstName: String?
        var lastName: String?
        var twitterUsername: String?
        var portfolioURL: String?
        var bio: String?
        var location: String?
        var instagramUsername: String?
        var totalCollections: Int?
        var totalLikes: Int?
        var totalPhotos: Int?
        var acceptedTos: Bool?
    
        enum CodingKeys: String, CodingKey {
            case id = "id"
            case updatedAt = "updated_at"
            case username = "username"
            case name = "name"
            case firstName = "first_name"
            case lastName = "last_name"
            case twitterUsername = "twitter_username"
            case portfolioURL = "portfolio_url"
            case bio = "bio"
            case location = "location"
            case instagramUsername = "instagram_username"
            case totalCollections = "total_collections"
            case totalLikes = "total_likes"
            case totalPhotos = "total_photos"
            case acceptedTos = "accepted_tos"
        }
    }
    
    // MARK: - Urls
    struct Urls: Codable {
        var raw: String?
        var full: String?
        var regular: String?
        var small: String?
        var thumb: String?
    
        enum CodingKeys: String, CodingKey {
            case raw = "raw"
            case full = "full"
            case regular = "regular"
            case small = "small"
            case thumb = "thumb"
        }
    }
    typealias Photo = [Photos]

**Network Call:**

 func downloadImage(from urlString: String, completed: @escaping (UIImage?) -> Void) {  
         let cacheKey = NSString(string: urlString) //creates cacheKey to store in image variable
        let imagesBaseURLSTring = imageURL.urls?.thumb ?? "No image"
        
        guard let url = URL(string: imagesBaseURLSTring) else {
            completed(nil)
            return
        }
        
        if let image = cache.object(forKey: cacheKey) {  //check if image is there
            completed(image)
            return
        }
        let task = URLSession.shared.dataTask(with: url) { [weak self] data, response, error in
            guard let self = self,
                  error == nil,
                  let response = response as? HTTPURLResponse, response.statusCode == 200,
                  let data = data,
                  let image = UIImage(data: data) else {
                completed(nil)
                return
            }
            self.cache.setObject(image, forKey: cacheKey)
            completed(image)
        }
        task.resume()
    }
    

Update UI:
    

    func setTableCell(_ photos:Photos){
                updateUI(userName: photos.user?.username, fullName:photos.user?.name, date: photos.createdAt, photo: photos.urls?.thumb)
            }
           

 
private func updateUI(userName:String?,fullName:String?,date:String?,photo:String?){
            self.userName.text = userName
            self.fullName.text = fullName
            self.date.text = date
            downloadImage(photo ?? "")
        }
        
        func downloadImage(_ url:String)  {
            NetworkManger.shared.downloadImage(from:url){ [weak self] image in
                   guard let self = self else { return }
                   DispatchQueue.main.async {
                    self.photoImage.image = image
                   }
                
            }
        }

Upvotes: 0

Views: 61

Answers (1)

Manish Punia
Manish Punia

Reputation: 877

If you try to put debug points and check the flow you will find out you have issue with following peace of code:

let cacheKey = NSString(string: urlString) //creates cacheKey to store in image variable
    let imagesBaseURLSTring = imageURL.urls?.thumb ?? "No image"
    // Here imagesBaseURLSTring is nil, so image is not downloaded and it is completed with nil. imagesBaseURLSTring is nil because of imageURL.urls is nil
    guard let url = URL(string: imagesBaseURLSTring) else {
        completed(nil)
        return
    }

Here imagesBaseURLSTring is nil, so image is not downloaded and it is completed with nil. imagesBaseURLSTring is nil because of imageURL.urls is nil. Please check your logic, why it is nil.

Just for testing your downloading part you can check with following :

//let imagesBaseURLSTring = imageURL.urls?.thumb ?? "No image"
let imagesBaseURLSTring = urlString

Upvotes: 1

Related Questions