006 [Translate] Haneke (a swfit iOS cache class)

Source: Internet
Author: User

GitHub Project Address: Https://github.com/Haneke/HanekeSwift

Haneke is a lightweight IOS class written in Swift, which is known for its ease of use (design-decisions-behind-haneke-1-0), how simple is it?

If you want to initialize a JSON cache, get the target from the URL :

Let cache = cache<json> (name: "GitHub") Let URL = Nsurl (string: "Https://api.github.com/users/haneke") Cache.fetch (Url:url). onsuccess {JSON in   println (json.dictionary?[" Bio "])}

It's that simple.

      haneke  also provides memory cache and lru (minimum use algorithm) Flash cache, supported formats are   Uiimage, nsdata  json,  string   et cetera ... in other words, as long as it is capable of reading and writing for  data

In addition,Haneke is very good at handling picture tasks: The image size can be handled automatically without extra action, which is done in the background, allowing the main UI to flow more smoothly. Loading, scaling the picture, caching and displaying the appropriate picture only requires a single line of code:

1 imageView.hnk_setImageFromURL(url)

Some features :

        • UIImage, nsdata, JSON and String caching Direct support
        • First-level cache - memory cache using nscache
        • Secondary cache - flash cache writes files using the LRU algorithm
        • Network operations or flash data acquisition operations using asynchronous methods
        • All flash related operations are done in the background
        • Thread Safety
        • A memory warning is received or there is not enough flash space to automatically clean up excess cache
        • After extensive use-case Testing
        • You can define custom format extensions, support other types, or perform other custom fetch operations

Especially for images:

        • You do not need to configure Uiimageview and UIButton to use the cache for uitableview and Uicollectionview 's cell reuse has been optimized for performance.
        • Background image processing (solution, compression)
        • IOS 8.0+
        • Xcode 6.0

The requirements are iOS 8.0 and the above may be harsh, because Apple just released the data is the iOS8 share or only 48%, but if it is a new project, it can be fully focused on Haneke.

integration into the project :

Haneke packaged as a Swift framework . The simplest method of introduction at present

      1. Drag the haneke.xcodeproj to your project .
      2. The selected project Target. Find Build phases .
      3. Expand , join haneke.framework.
      4. Click + , then select New Copy Files Phase. Add haneke.framework.
        1. Import Haneke .

using the cache:

Haneke provides shared for UIImage, nsdata, JSON, and String Cache. You can also create your own cache object.

The cache is Key-value . As an example , save the cache and retrieve it again:

Let cache = Haneke.sharedDataCachecache.set (Value:data, Key: "Funny-games.mp4")//Then ... cache.fetch (key: " Funny-games.mp4 "). onsuccess {data    in//data-related operations can be done here}

In most cases, we always go to the network or flash to re-read the value, but Haneke provides a convenient way to get back to the first example, this time using the shared cache:

Let cache = Haneke.sharedjsoncachelet URL = Nsurl (string: "Https://api.github.com/users/haneke") Cache.fetch (Url:url). onsuccess {JSON in   println (json.dictionary?[" Bio "])}

This request will first attempt to read from the memory cache, then flash and Nsurlcache, if the data is not found, then Haneke will retrieve the network data and then cache, in this pest, the URL itself as a key to save. more custom actions can be referred to formats, supporting additional types or Implementingcustom fetchers.

? more support for images

For images,Haneke provides uiimageview , UIButton, and uitableview and more optimizations and simpler ways to uicollectionview cell reuse . Pictures can be well compressed and stored in the cache.

Set up a network picture imageview.hnk_setimagefromurl (URL)//manually set up a picture. You need to customize the key name. Imageview.hnk_setimage (image, Key:key)

The above code :

        1. If the cache succeeds, the cache (memory or flash) gets a picture of the right size (and Uiimageview's bounds and Contenmode), all in the background, so it's not going to be a card, um.
        2. If not cached, from the target location to obtain the image will be compressed to produce a suitable size of the picture, also in the background, joined in the Nsurlcache can be found, then from the Nsurlcache to get.
        3. Sets the picture with an animated effect.
        4. If UIIMAGEVIEWV is being reused in the above operation, it will not operate.
        5. Image after the cache operation
        6. If necessary, the least-used images in the cache are cleaned up.


Formats allows for changes before checking the size of the flash cache and all caches, and then lifting a chestnut,uiimageview extension with a format To zoom in on the image size to get the appropriate image.

You can also customize the Formats , for example, if you want to limit the size of the disk cache to tenMB or a fillet to the picture:

Let cache = Haneke.sharedimagecachelet Iconformat = format<uiimage> (name: "Icons", diskcapacity:10 * 1024 * 1024) { Image in    return imagebyroundingcornersofimage (image)}cache.addformat (iconformat) Let URL = Nsurl (string: "http:/ /haneke.io/icon.png ") Cache.fetch (Url:url, FormatName:" Icons "). onsuccess {image    in//Picture rounded ...}

We just need to tell Haneke that we need the "icons" format, and that Haneke will help us out in the background, we just have to wait for the results.

Formats can also be used in UIKit extensions:

Imageview.hnk_setimagefromurl (URL, Format:iconformat)


According to the method of obtaining URLs or paths is quite simple, the network obtains the example:

12345 let URL =  nsurl ( string:  "http://haneke.io/icon.png" ) let fetcher = networkfetcher<uiimage> (url:url) cache.fetch (fetcher:fetcher). onsuccess {image in       //What you can do with image here.

The cost of acquiring raw data from a network or flash memory is often high, andfetchers , like a proxy, initiates a fetch only when Haneke really needs it. In addition,if Fetcher is fetching data from the network, Fetcher caches the acquired data.

Custom fetchers

Hanekeprovides two specialFetchers:Networkfetcher<t>and diskfetcher<t>. You can also inherit fetchers<t> customize fetchers fetchers   from outside the network and flash core data). You can even customize  haneke  to access the network or flash memory, for example,     (similar to obj-c in afnetworking)  fetcer fetcher<t>  

        • provide key   ( networkfetchernsurl.absolutestring)  
        • get operations in the background, Then provide success or failure in the main thread after the closure ( closures: similar to Obj- C)

Fetchers is generic, so the only restriction on it is that it must conform to type matching (dataconvertible). as long as the data can be saved as the Haneke, it can be cached. Specific requirements Follow the dataconvertible and datarepresentable protocols:

Public protocol dataconvertible {    Typealias resultclass func convertfromdata (data:nsdata), Result?} Public protocol Datarepresentable {func asdata ()-nsdata!}

If you want nsdictionary to increase cache support :

Extension nsdictionary:dataconvertible, datarepresentable {public Typealias Result = Nsdictionarypublic class func Conve Rtfromdata (data:nsdata), Result? {        return Nskeyedunarchiver.unarchiveobjectwithdata (data) as? Nsdictionary    }public func asdata () nsdata! {        return nskeyedarchiver.archiveddatawithrootobject (self)    }}

After that, it's easy to cache the nsdictionary :

Let cache = cache<nsdictionary> (name: "Dictionaries")

Project Progress:

Haneke Swift is an ongoing project and its API is not very stable at the moment .


006 [Translate] Haneke (a swfit iOS cache class)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.