mardi 17 mars 2020

MVVM Async UIImage loading from network on iOS Swift

I have been using MVC since my first app on iOS... now i want to try MVVM.

My approach is that a Model can contain the remote URL and the ViewModel makes the request to download the image. (pushing then to binded view)... I think this is suitable for not make a network request in Views (or worse cells!)

class Person: NSObject {
    var firstName: String?
    var lastName: String?
    var avatarURL: URL?
}
class PersonEntryViewModel {
    var name:String?
    var avatarImage:UIImage?

    init(person: Person?) {
        super.init()
        // omitted: binding self.name based on person.firstName & person.lastName
        var request: URLRequest? = nil
        if let avatarURL = person?.avatarURL {
            request = URLRequest(url: avatarURL)
        }
        fetchImageFromNetwork({ response, data in
            if let data = data {
                avatarImage = UIImage(data: data)
            }
        })
    }
}

What do you think?

My doubt is about memory. I could have a big array of viewmodels filled with UIImages...

Aucun commentaire:

Enregistrer un commentaire