Why do all the async image loading (SDWebImage, AF

2019-07-09 00:13发布

问题:

Am I missing something? Wouldn't allow it to be used with UIImage be more versatile than just UIImageView? You could hand the UIImage around and use it for different things, where a UIImageView can really only be added to the view.

My initial thought was what if you hand it to another class and the UIImage hasn't loaded yet, it would receive nil and not be passed anything new. But the same applies if you pass a UIImageView, wouldn't it?

回答1:

AFNetworking

You're right, the AFNetworking category implementation (UIImageView+AFNetworking) is bare-bones.

But you're missing AFImageResponseSerializer, which validates and decodes images and provides a few options for handling them. (In the old 1.x version of AFNetworking, this functionality is in AFImageRequestOperation.)

SDWebImage

Similarly, you're only looking at the very basic implementation of SDWebImage. There are a LOT of options here, so I suggest you review some of the other classes, but at the most basic level, you can get a UIImage like this:

SDWebImageManager *manager = [SDWebImageManager sharedManager];
[manager downloadWithURL:imageURL
                 options:kNilOptions
                 progress:^(NSUInteger receivedSize, NSUInteger expectedSize)
                 {
                     // update a progress view
                 }
                 completed:^(UIImage *image, NSError *error, SDImageCacheType cacheType, BOOL finished)
                 {
                     if (image)
                     {
                         // Do something with the image; cacheType tells you if it was cached or not.
                     }
                 }];

Asynchronous loading

What if you hand it to another class and the UIImage hasn't loaded yet?

Well, it's all loaded asynchronously, so the completion block wouldn't get called until the UIImage was loaded.