简体   繁体   中英

How to download image using RxSwift and Alamofire?

I have some issues with the image also when I try to scroll after the images was loaded.

I researched about the incorrect image being displayed and I think I have to cached the image that was loaded. Is that the standard way to do this?

I'm quite proficient in Android and I'm pretty sure the fresco/picasso library do this already which I think is not in iOS.

Can someone point me to the right direction?

Thank you

class PostTableViewCell: UITableViewCell {

    @IBOutlet weak var fileView: UIImageView!

    @IBOutlet weak var messageLabel: UILabel!

    let disposeBag = DisposeBag()

    var postViewModel: PostViewModel? {
        didSet {
            guard let pvm = postViewModel else {
                return
            }

            Alamofire.request(pvm.file).responseImage{ response in
                if let image = response.result.value {
                    self.fileView.image = image
                    self.fileView.setNeedsLayout()
                }
            }

            pvm.messageText.bindTo(messageLabel.rx.text).addDisposableTo(disposeBag)
        }
    }
}

class PostViewModel {
    private let post: Post
    let disposeBag = DisposeBag()

    var fileText: BehaviorSubject<String>
    var messageText: BehaviorSubject<String>

    var file: String {
        return post.file!
    }

    init(post: Post)
    {
        self.post = post
        fileText = BehaviorSubject<String>(value: post.file!)
        fileText.subscribe(onNext: {(file) in
            post.file = file
        }).addDisposableTo(disposeBag)

        messageText = BehaviorSubject<String>(value: post.message!)
        messageText.subscribe(onNext: {(message) in
            post.message = message
        }).addDisposableTo(disposeBag)
    }
}

When you download something, for example, with Alamofire. You're going off the main thread (it's an asynchronous job). So when you get your data, you have to push it back to the main thread again.

Have you tried:

Alamofire.request(pvm.file).responseImage{ response in
    DispatchQueue.main.async {
        if let image = response.result.value {
            self.fileView.image = image
            self.fileView.setNeedsLayout()
        }
    }
}

Also, the response.result.value most likely isn't an UIImage, but it's some form of data. I don't know what's inside of your response.result.value but it's possible you have to init your UIImage with the data init.

if let image = UIImage(data: response.result.value) {        
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM