swift_035 (Kingfisher, Swift's Third Party Library)

Keywords: PHP Swift

[Rapid Learning Swift Third Party Library] Kingfisher

Kingfisher is a lightweight online photo library for downloading and caching. Downloading and caching are asynchronous operations. The downloaded images will be cached in memory and locally, which greatly improves the app experience.

(Document address: http://cocoadocs.org/docsets/Kingfisher/1.6.1/Typealiases.html#/s:10Kingfisher32ImageDownloaderCompletionHandler)

Catalog

Other operations

In addition, you need to add Kingfisher's directory at Target - > Project Name - > Build Settings - > Search Paths - > User Header Search Paths:

Finally, add the following to the class you need to use Kingfisher:

import Kingfisher

Basic operation

        let url = NSURL(string: "http://www.51work6.com/service/download.php?email=scuxiatian@foxmail.com&FileName=test1.jpg")!;

        //Open the image of the url address
        imageView.kf_setImageWithURL(url)

        //If the opening fails, open the picture of the placeholder Image parameter
        imageView.kf_setImageWithURL(url, placeholderImage: UIImage(named: "sps.png"))

        //Open the image in the resource. If it is not in the local cache, it will be downloaded from the url address with keywords."MyImage"Save it for next use
        let resource = Resource(downloadURL: url, cacheKey: "MyImage");
        imageView.kf_setImageWithResource(resource);

The operation results are as follows:

Using optionsInfo parameters

        //Force refresh, whether or not the image is in the cache, to reload from the url address
        imageView.kf_setImageWithURL(url, placeholderImage: nil, optionsInfo: [.ForceRefresh])

        //Custom keywords are"MyImage"Of ImageCache
        let myCache = ImageCache(name: "MyImage");
        //Store open pictures in the cache of the specified keyword instead of the default cache
        imageView.kf_setImageWithURL(url, placeholderImage: nil, optionsInfo: [.TargetCache(myCache)])

        //Pictures appear in fade-in mode, animation continues1second
        imageView.kf_setImageWithURL(url, placeholderImage: nil, optionsInfo: [.Transition(ImageTransition.Fade(1))])

        //Options Info parameters can accept multiple conditions at the same time
        imageView.kf_setImageWithURL(url, placeholderImage: nil, optionsInfo: [.ForceRefresh,.TargetCache(myCache),.Transition(ImageTransition.Fade(1))])

callback

        imageView.kf_setImageWithURL(url, placeholderImage: nil, optionsInfo: nil, 
        //Progress callback function
        progressBlock: { (receivedSize, totalSize) in
            print(receivedSize / totalSize)
        //Complete callback function
        { (image, error, cacheType, imageURL) in
            print("complete")
        }

Cancellation of tasks

If the downloaded image is no longer used, it can stop the task. It is mostly used for cell in tableView and collectionview. When the image is not downloaded, the user slides the interface and causes the cell to disappear.

        imageView.kf_setImageWithURL(url)
        //Stop Picture Retrieval
        imageView.kf_cancelDownloadTask();

You can also use the return value of the kf_setImageWithURL function (type RetrieveImageTask) for more administrative operations.

        let task = imageView.kf_setImageWithURL(url)
        //Cancellation of tasks
        task.cancel();

Downloader

Custom downloader parameters

        //Get the downloader
        let downloader = KingfisherManager.sharedManager.downloader
        //Set timeout, default is15Wonderful
        downloader.downloadTimeout = 5
        //Content in request Modifier starts executing before downloading
        downloader.requestModifier = {
            (request: NSMutableURLRequest) in
            self.imageView.image = UIImage(named: "sps.png")
        }
        //Setting Trust host
        downloader.trustedHosts = Set(["httpbin.org"])

Caching system

Custom cache parameters

        //Getting Cache
        let cache = KingfisherManager.sharedManager.cache
        //Set the maximum disk cache to 50Mb, default to unlimited
        cache.maxDiskCacheSize = 50 * 1024 * 1024
        //Set maximum caching time to 1 day, default to 1 week
        cache.maxCachePeriodInSecond = 60 * 60 * 24
        //Calculate the disk size occupied by the cache
        cache.calculateDiskCacheSizeWithCompletionHandler { (size) in
            print(size)
        }
        //Clear memory cache
        cache.clearMemoryCache()
        //Clear the disk cache
        cache.clearDiskCache()
        //Emptying failures and excessive caching
        cache.cleanExpiredDiskCache()

Prefetch

Some pictures are pre-fetched into the cache before they are displayed on the screen. Mainly used to avoid multiple requests when you can predict the next use of image resources.

        let urlString1 = "http://www.51work6.com/service/download.php?email=scuxiatian@foxmail.com&FileName=test1.jpg"
        let urlString2 = "http://www.51work6.com/service/download.php?email=scuxiatian@foxmail.com&FileName=test2.jpg"

        let urls = [urlString1,urlString2].map{NSURL(string: $0 )!}
        let prefetcher = ImagePrefetcher(urls: urls, optionsInfo: nil, progressBlock: nil) { (skippedResources, failedResources, completedResources) in
            print("These resources are prefetched:\(completedResources)")
        }
        //Start prefetching, prefetching successful images in the same way as cached images in ImageCache
        prefetcher.start()
        //Stop prefetching
        prefetcher.stop()

Dynamic picture

It only needs one line of code to load the dynamic picture. Set the image View to Animated Image View. It can also be loaded without setting, but this setting is recommended when the dynamic picture is large.

        imageView = AnimatedImageView()
        imageView.kf_setImageWithURL(url)


Posted by sbarros on Sun, 09 Jun 2019 17:57:50 -0700