Sfoglia il codice sorgente

Add documentation.

onevcat 10 anni fa
parent
commit
cd7f68e9a5

+ 110 - 7
Kingfisher/ImageCache.swift

@@ -34,37 +34,55 @@ private let processQueueName = "com.onevcat.Kingfisher.ImageCache.processQueue"
 private let defaultCacheInstance = ImageCache(name: defaultCacheName)
 private let defaultMaxCachePeriodInSecond: NSTimeInterval = 60 * 60 * 24 * 7 //Cache exists for 1 week
 
-
 public typealias RetrieveImageDiskTask = dispatch_block_t
 
+/**
+Cache type of a cached image.
+
+- Memory: The image is cached in memory.
+- Disk:   The image is cached in disk.
+*/
 public enum CacheType {
     case Memory, Disk
 }
 
 public class ImageCache {
+
+    //Memory
+    private let memoryCache = NSCache()
     
-    public var maxCachePeriodInSecond = defaultMaxCachePeriodInSecond
+    /// The largest cache cost of memory cache. The total cost is pixel count of all cached images in memory.
     public var maxMemoryCost: UInt = 0 {
         didSet {
             self.memoryCache.totalCostLimit = Int(maxMemoryCost)
         }
     }
-    public var maxDiskCacheSize: UInt = 0
-    
-    //Memory
-    private let memoryCache = NSCache()
     
     //Disk
     private let ioQueue = dispatch_queue_create(ioQueueName, DISPATCH_QUEUE_SERIAL)
     private let diskCachePath: String
     private var fileManager: NSFileManager!
     
+    /// The longest time duration of the cache being stored in disk. Default is 1 week.
+    public var maxCachePeriodInSecond = defaultMaxCachePeriodInSecond
+    
+    /// The largest disk size can be taken for the cache. It is the total allocated size of the file in bytes. Default is 0, which means no limit.
+    public var maxDiskCacheSize: UInt = 0
+    
     private let processQueue = dispatch_queue_create(processQueueName, DISPATCH_QUEUE_CONCURRENT)
     
+    /// The default cache.
     public class var defaultCache: ImageCache {
         return defaultCacheInstance
     }
     
+    /**
+    Init method. Passing a name for the cache. It represents a cache folder in the memory and disk.
+    
+    :param: name Name of the cache.
+    
+    :returns: The cache object.
+    */
     public init(name: String) {
         let cacheName = cacheReverseDNS + name
         memoryCache.name = cacheName
@@ -88,11 +106,26 @@ public class ImageCache {
 
 // MARK: - Store & Remove
 public extension ImageCache {
+    /**
+    Store an image to cache. It will be saved to both memory and disk. 
+    It is an async operation, if you need to do something about the stored image, use `-storeImage:forKey:toDisk:completionHandler:` 
+    instead.
     
+    :param: image The image will be stored.
+    :param: key   Key for the image.
+    */
     public func storeImage(image: UIImage, forKey key: String) {
         storeImage(image, forKey: key, toDisk: true, completionHandler: nil)
     }
     
+    /**
+    Store an image to cache. It is an async operation.
+    
+    :param: image             The image will be stored.
+    :param: key               Key for the image.
+    :param: toDisk            Whether this image should be cached to disk or not. If false, the image will be only cached in memory.
+    :param: completionHandler Called when stroe operation completes.
+    */
     public func storeImage(image: UIImage, forKey key: String, toDisk: Bool, completionHandler: (() -> ())?) {
         memoryCache.setObject(image, forKey: key, cost: image.kf_imageCost)
         
@@ -126,10 +159,24 @@ public extension ImageCache {
         }
     }
     
+    /**
+    Remove the image for key for the cache. It will be opted out from both memory and disk.
+    It is an async operation, if you need to do something about the stored image, use `-removeImageForKey:fromDisk:completionHandler:` 
+    instead.
+    
+    :param: key Key for the image.
+    */
     public func removeImageForKey(key: String) {
         removeImageForKey(key, fromDisk: true, completionHandler: nil)
     }
     
+    /**
+    Remove the image for key for the cache. It is an async operation.
+    
+    :param: key               Key for the image.
+    :param: fromDisk          Whether this image should be removed from disk or not. If false, the image will be only removed from memory.
+    :param: completionHandler Called when removal operation completes.
+    */
     public func removeImageForKey(key: String, fromDisk: Bool, completionHandler: (() -> ())?) {
         memoryCache.removeObjectForKey(key)
         
@@ -153,6 +200,15 @@ public extension ImageCache {
 
 // MARK: - Get data from cache
 extension ImageCache {
+    /**
+    Get an image for a key from memory or disk.
+    
+    :param: key               Key for the image.
+    :param: options           Options of retriving image.
+    :param: completionHandler Called when getting operation completes with image result and cached type of this image. If there is no such key cached, the image will be `nil`.
+    
+    :returns: The retriving task.
+    */
     public func retrieveImageForKey(key: String, options:KingfisherManager.Options, completionHandler: ((UIImage?, CacheType!) -> ())?) -> RetrieveImageDiskTask? {
         // No completion handler. Not start working and early return.
         if (completionHandler == nil) {
@@ -214,10 +270,24 @@ extension ImageCache {
         return block
     }
     
+    /**
+    Get an image for a key from memory.
+    
+    :param: key Key for the image.
+    
+    :returns: The image object if it is cached, or `nil` if there is no such key in the cache.
+    */
     public func retriveImageInMemoryCaheForKey(key: String) -> UIImage? {
         return memoryCache.objectForKey(key) as? UIImage
     }
     
+    /**
+    Get an image for a key from disk.
+    
+    :param: key Key for the image.
+    
+    :returns: The image object if it is cached, or `nil` if there is no such key in the cache.
+    */
     public func retriveImageInDiskCacheForKey(key: String) -> UIImage? {
         return diskImageForKey(key)
     }
@@ -225,14 +295,25 @@ extension ImageCache {
 
 // MARK: - Clear & Clean
 extension ImageCache {
+    /**
+    Clear memory cache.
+    */
     @objc public func clearMemoryCache() {
         memoryCache.removeAllObjects()
     }
     
+    /**
+    Clear disk cache. This is an async operation.
+    */
     public func clearDiskCache() {
         clearDiskCacheWithCompletionHandler(nil)
     }
     
+    /**
+    Clear disk cache. This is an async operation.
+    
+    :param: completionHander Called after the operation completes.
+    */
     public func clearDiskCacheWithCompletionHandler(completionHander: (()->())?) {
         dispatch_async(ioQueue, { () -> Void in
             self.fileManager.removeItemAtPath(self.diskCachePath, error: nil)
@@ -246,10 +327,18 @@ extension ImageCache {
         })
     }
     
+    /**
+    Clean expired disk cache. This is an async operation.
+    */
     @objc public func cleanExpiredDiskCache() {
         cleanExpiredDiskCacheWithCompletionHander(nil)
     }
     
+    /**
+    Clean expired disk cache. This is an async operation.
+    
+    :param: completionHandler Called after the operation completes.
+    */
     public func cleanExpiredDiskCacheWithCompletionHander(completionHandler: (()->())?) {
         // Do things in cocurrent io queue
         dispatch_async(ioQueue, { () -> Void in
@@ -338,6 +427,11 @@ extension ImageCache {
         })
     }
     
+    /**
+    Clean expired disk cache when app in background. This is an async operation.
+    In most cases, you should not call this method explicitly. 
+    It will be called automatically when `UIApplicationDidEnterBackgroundNotification` received.
+    */
     @objc public func backgroundCleanExpiredDiskCache() {
         
         func endBackgroundTask(inout task: UIBackgroundTaskIdentifier) {
@@ -361,12 +455,21 @@ extension ImageCache {
 // MARK: - Check cache statue
 public extension ImageCache {
     
-    // For Objective-C compatibility, we can not use tuple
+    /**
+    *  Cache result for checking whether an image is cached for a key.
+    */
     public struct CacheCheckResult {
         public let cached: Bool
         public let cacheType: CacheType?
     }
     
+    /**
+    Check whether an image is cached for a key.
+    
+    :param: key Key for the image.
+    
+    :returns: The check result.
+    */
     public func isImageCachedForKey(key: String) -> CacheCheckResult {
         if memoryCache.objectForKey(key) != nil {
             return CacheCheckResult(cached: true, cacheType: .Memory)

+ 18 - 3
Kingfisher/ImageDownloader.swift

@@ -26,6 +26,7 @@ public class ImageDownloader: NSObject {
     }
     
     // MARK: - Public property
+    /// The duration before the download is timeout. Default is 15 seconds.
     public var downloadTimeout: NSTimeInterval = 15.0
     
     // MARK: - Internal property
@@ -37,6 +38,7 @@ public class ImageDownloader: NSObject {
     var fetchLoads = [NSURL: ImageFetchLoad]()
     
     // MARK: - Public method
+    /// The default downloader.
     public class var defaultDownloader: ImageDownloader {
         return instance
     }
@@ -44,7 +46,13 @@ public class ImageDownloader: NSObject {
 
 // MARK: - Download method
 public extension ImageDownloader {
+    /**
+    Download an image with a url.
     
+    :param: url               Target url.
+    :param: progressBlock     Called when the download progress updated.
+    :param: completionHandler Called when the download progress finishes.
+    */
     public func downloadImageWithURL(url: NSURL,
         progressBlock: ImageDownloaderProgressBlock?,
         completionHandler: ImageDownloaderCompletionHandler?)
@@ -52,6 +60,14 @@ public extension ImageDownloader {
         downloadImageWithURL(url, options: KingfisherManager.OptionsNone, progressBlock: progressBlock, completionHandler: completionHandler)
     }
     
+    /**
+    Download an image with a url and option.
+    
+    :param: url               Target url.
+    :param: options           The options could control download behavior. See `KingfisherManager.Options`
+    :param: progressBlock     Called when the download progress updated.
+    :param: completionHandler Called when the download progress finishes.
+    */
     public func downloadImageWithURL(url: NSURL,
         options: KingfisherManager.Options,
         progressBlock: ImageDownloaderProgressBlock?,
@@ -64,7 +80,6 @@ public extension ImageDownloader {
             completionHandler: completionHandler)
     }
     
-    
     internal func downloadImageWithURL(url: NSURL,
                        retrieveImagetask: RetrieveImageTask?,
                                  options: KingfisherManager.Options,
@@ -168,10 +183,10 @@ extension ImageDownloader: NSURLSessionDataDelegate {
                         }
 
                     } else {
-                        self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: WebImageError.BadData.rawValue, userInfo: nil), imageURL: url)
+                        self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: url)
                     }
                 } else {
-                    self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: WebImageError.BadData.rawValue, userInfo: nil), imageURL: url)
+                    self.callbackWithImage(nil, error: NSError(domain: KingfisherErrorDomain, code: KingfisherError.BadData.rawValue, userInfo: nil), imageURL: url)
                 }
                 
                 self.cleanForURL(url)

+ 1 - 1
Kingfisher/Kingfisher.h

@@ -4,7 +4,7 @@
 //
 //  Created by Wei Wang on 15/4/6.
 //
-//  Copyright (c) 2015 Wei Wang (onevcat)
+//  Copyright (c) 2015 Wei Wang <onevcat@gmail.com>
 //
 //  Permission is hereby granted, free of charge, to any person obtaining a copy
 //  of this software and associated documentation files (the "Software"), to deal

+ 37 - 2
Kingfisher/KingfisherManager.swift

@@ -26,11 +26,18 @@
 
 import Foundation
 
+/**
+*  RetrieveImageTask represents a task of image retrieving process.
+*  It contains an async task of getting image from disk and from network.
+*/
 public class RetrieveImageTask {
     
     var diskRetriveTask: RetrieveImageDiskTask?
     var downloadTask: RetrieveImageDownloadTask?
     
+    /**
+    Cancel current task. If this task does not begin or already done, do nothing.
+    */
     public func cancel() {
         if let diskRetriveTask = diskRetriveTask {
             dispatch_block_cancel(diskRetriveTask)
@@ -44,14 +51,22 @@ public class RetrieveImageTask {
 
 public let KingfisherErrorDomain = "com.onevcat.Kingfisher.Error"
 
-public enum WebImageError: Int {
+/**
+The error code.
+
+- BadData: The downloaded data is not an image or the data is corrupted.
+*/
+public enum KingfisherError: Int {
     case BadData = 10000
 }
 
 private let instance = KingfisherManager()
 
+/**
+*  Main manager class of Kingfisher
+*/
 public class KingfisherManager {
-    
+
     public typealias Options = (forceRefresh: Bool, lowPriority: Bool, cacheMemoryOnly: Bool, shouldDecode: Bool)
     
     public static var OptionsNone: Options = {
@@ -62,15 +77,35 @@ public class KingfisherManager {
         return instance
     }
     
+    /// Cache used by this manager
     public var cache: ImageCache
+    
+    /// Downloader used by this manager
     public var downloader: ImageDownloader
     
+    /**
+    Default init method
+    
+    :returns: A Kingfisher manager object with default cache and default downloader.
+    */
     public init() {
         cache = ImageCache.defaultCache
         downloader = ImageDownloader.defaultDownloader
     }
 
+    /**
+    Get an image with url as the key.
+    If KingfisherOptions.None is used as `options`, Kingfisher will seek the image in memory and disk first.
+    If not found, it will download the image at url and cache it.
+    These default behaviors could be adjusted by passing different options. See `KingfisherOptions` for more.
+    
+    :param: url               The image url.
+    :param: options           Options controlling manager behavior.
+    :param: progressBlock     Called every time downloaded data changed. This could be used as a progress UI.
+    :param: completionHandler Called when the whole retriving process finished.
     
+    :returns: A `RetrieveImageTask` task object. You can use this object to cancel the task.
+    */
     public func retriveImageWithURL(url: NSURL,
                                 options: KingfisherOptions,
                           progressBlock:DownloadProgressBlock?,

+ 12 - 0
Kingfisher/KingfisherOptions.swift

@@ -26,6 +26,9 @@
 
 import Foundation
 
+/**
+*  Options to control Kingfisher behaviors.
+*/
 public struct KingfisherOptions : RawOptionSetType {
     typealias RawValue = UInt
     private var value: UInt = 0
@@ -36,9 +39,18 @@ public struct KingfisherOptions : RawOptionSetType {
     static func fromMask(raw: UInt) -> KingfisherOptions { return self(raw) }
     public var rawValue: UInt { return self.value }
     
+    /// None options. Kingfisher will keep its default behavior.
     public static var None: KingfisherOptions { return self(0) }
+    
+    /// Download in a low priority.
     public static var LowPriority: KingfisherOptions { return KingfisherOptions(1 << 0) }
+    
+    /// Ignore cache. Always download the image and cache it again.
     public static var ForceRefresh: KingfisherOptions { return KingfisherOptions(1 << 1) }
+    
+    /// Only cache downloaded image to memory, not cache in disk.
     public static var CacheMemoryOnly: KingfisherOptions { return KingfisherOptions(1 << 2) }
+    
+    /// Decode the image in background thread before using.
     public static var BackgroundDecode: KingfisherOptions { return KingfisherOptions(1 << 3) }
 }

+ 2 - 2
Kingfisher/String+MD5.swift

@@ -67,7 +67,7 @@ func arrayOfBytes<T>(value:T, length:Int? = nil) -> [UInt8] {
 
 extension Int {
     /** Array of bytes with optional padding (little-endian) */
-    public func bytes(_ totalBytes: Int = sizeof(Int)) -> [UInt8] {
+    func bytes(_ totalBytes: Int = sizeof(Int)) -> [UInt8] {
         return arrayOfBytes(self, length: totalBytes)
     }
     
@@ -76,7 +76,7 @@ extension Int {
 extension NSMutableData {
     
     /** Convenient way to append bytes */
-    internal func appendBytes(arrayOfBytes: [UInt8]) {
+    func appendBytes(arrayOfBytes: [UInt8]) {
         self.appendBytes(arrayOfBytes, length: arrayOfBytes.count)
     }
     

+ 48 - 0
Kingfisher/UIImageView+Kingfisher.swift

@@ -31,17 +31,43 @@ public typealias CompletionHandler = ((image: UIImage?, error: NSError?, imageUR
 
 // MARK: - Set Images
 public extension UIImageView {
+    /**
+    Set an image with a url.
+    It will ask for Kingfisher's manager to get the image for the url.
+    The memory and disk will be searched first. If the manager does not find it, it will try to download the image at this url and store it for next use.
+    
+    :param: url The url of image.
+    
+    :returns: A task represents the retriving process.
+    */
     public func kf_setImageWithURL(url: NSURL) -> RetrieveImageTask
     {
         return kf_setImageWithURL(url, placeHolderImage: nil, options: KingfisherOptions.None, progressBlock: nil, completionHandler: nil)
     }
     
+    /**
+    Set an image with a url and a place holder image.
+    
+    :param: url              The url of image.
+    :param: placeHolderImage A placeholder image when retrieving the image at url.
+    
+    :returns: A task represents the retriving process.
+    */
     public func kf_setImageWithURL(url: NSURL,
                       placeHolderImage: UIImage?) -> RetrieveImageTask
     {
         return kf_setImageWithURL(url, placeHolderImage: placeHolderImage, options: KingfisherOptions.None, progressBlock: nil, completionHandler: nil)
     }
     
+    /**
+    Set an image with a url, a place holder image and options.
+    
+    :param: url              The url of image.
+    :param: placeHolderImage A placeholder image when retrieving the image at url.
+    :param: options          Options which could control some behaviors. See `KingfisherOptions` for more.
+    
+    :returns: A task represents the retriving process.
+    */
     public func kf_setImageWithURL(url: NSURL,
                       placeHolderImage: UIImage?,
                                options: KingfisherOptions) -> RetrieveImageTask
@@ -49,6 +75,16 @@ public extension UIImageView {
         return kf_setImageWithURL(url, placeHolderImage: placeHolderImage, options: options, progressBlock: nil, completionHandler: nil)
     }
     
+    /**
+    Set an image with a url, a place holder image, options and completion handler.
+    
+    :param: url               The url of image.
+    :param: placeHolderImage  A placeholder image when retrieving the image at url.
+    :param: options           Options which could control some behaviors. See `KingfisherOptions` for more.
+    :param: completionHandler Called when the image retrieved and set.
+    
+    :returns: A task represents the retriving process.
+    */
     public func kf_setImageWithURL(url: NSURL,
                       placeHolderImage: UIImage?,
                                options: KingfisherOptions,
@@ -57,6 +93,17 @@ public extension UIImageView {
         return kf_setImageWithURL(url, placeHolderImage: placeHolderImage, options: options, progressBlock: nil, completionHandler: completionHandler)
     }
     
+    /**
+    Set an image with a url, a place holder image, options, progress handler and completion handler.
+    
+    :param: url               The url of image.
+    :param: placeHolderImage  A placeholder image when retrieving the image at url.
+    :param: options           Options which could control some behaviors. See `KingfisherOptions` for more.
+    :param: progressBlock     Called when the image downloading progress gets updated.
+    :param: completionHandler Called when the image retrieved and set.
+    
+    :returns: A task represents the retriving process.
+    */
     public func kf_setImageWithURL(url: NSURL,
                       placeHolderImage: UIImage?,
                                options: KingfisherOptions,
@@ -88,6 +135,7 @@ public extension UIImageView {
 // MARK: - Associated Object
 private var lastUrlkey: Void?
 public extension UIImageView {
+    /// Get the image url binded to this image view. You can use `kf_setImage` methods to set it.
     public var kf_webUrl: NSURL? {
         get {
             return objc_getAssociatedObject(self, &lastUrlkey) as? NSURL