
Chun 是葉純俊開源在 Github 上的一個圖片緩存庫,採用 Swift 編寫。學 Swift 也有一段時間了,趁機把閱讀源碼過程中的一點心得記錄下來,與大家分享。
代碼組織
在 Swift 裡,善用 extension 來組織代碼能讓整個類變得更清晰易讀,對於 UITableViewDataSource 和 UITableViewDelegate 這類場景尤為明顯。Chun 項目裡的 Demo 就是這樣寫的:
class ViewController: UIViewController { override func viewDidLoad() { super.viewDidLoad() ... } } extension ViewController: UITableViewDataSource, UITableViewDelegate { func tableView(tableView: UITableView, numberOfRowsInSection section: Int) -> Int { ... } func tableView(tableView: UITableView, cellForRowAtIndexPath indexPath: NSIndexPath) -> UITableViewCell { ... } func tableView(tableView: UITableView, heightForRowAtIndexPath indexPath: NSIndexPath) -> CGFloat { ... } }而在 viewDidLoad 裡,為了避免初始化代碼越寫越長、影響可讀性,可以借助內嵌函數把代碼分段:
override func viewDidLoad() { super.viewDidLoad() func loadTableView() { ... } loadTableView() }動態添加屬性
在給 UIImageView 加載圖片時,我們最好能在對象裡記錄下它要加載的 URL,這可以通過 AssociatedObject 來實現。在 Swift 中,用一個私有計算屬性封裝一下會很乾淨:
private var imageURLForChun: NSURL? { get { return objc_getAssociatedObject(self, &key) as? NSURL } set (url) { objc_setAssociatedObject(self, &key, url, UInt(OBJC_ASSOCIATION_RETAIN_NONATOMIC)) } }這樣在調用的時候,它和真正的屬性幾乎沒有區別:
if let imageURL = self.imageURLForChun { ... }weak 與 unowned 的取捨
在避免循環強引用時,判斷標準很簡單:若某些時刻引用可能為空,就用 weak;若引用始終有值,則用 unowned。
在 Chun 項目裡,圖片加載完成後的回調用的是 weak,因為完全有可能圖片還沒下載完,UIImageView 就已經被銷毀了:
Chun.sharedInstance.fetchImageWithURL(url, complete: { [weak self](result: Result) -> Void in ... })而在查詢本地緩存時則用了 unowned,因為這裡的 self 是單例,永遠不會被銷毀:
cache.diskImageExistsWithKey(key, completion: { [unowned self](exist: Bool, diskURL: NSURL?) -> Void in ... })枚舉的優雅用法
用枚舉來表達返回結果是個很不錯的思路,我在《面向協議編程 - Swift 中的異常處理》裡曾詳細探討過。Chun 的用法是這樣的:
public enum Result { case Success(image: UIImage, fetchedImageURL: NSURL) case Error(error: NSError) }圖片加載完成後的回調則寫成:
public func fetchImageWithURL(url: NSURL, complete: (Result) -> Void) { let key = cacheKeyForRemoteURL(url) if let image = cache.imageForMemeoryCacheWithKey(key) { let result = Result.Success(image: image, fetchedImageURL: url) complete(result) } else { ... } }圖片渲染
直接從網絡下載回來的圖片並不能立刻使用,先把它解碼成位圖再渲染,能有效降低後續繪製的開銷:
func decodedImageWithImage(image: UIImage) -> UIImage { if image.images != nil { return image } let imageRef = image.CGImage let imageSize: CGSize = CGSizeMake(CGFloat(CGImageGetWidth(imageRef)), CGFloat(CGImageGetHeight(imageRef))) let imageRect = CGRectMake(0, 0, imageSize.width, imageSize.height) let colorSpace = CGColorSpaceCreateDeviceRGB() let originalBitmapInfo = CGImageGetBitmapInfo(imageRef) let alphaInfo = CGImageGetAlphaInfo(imageRef) var bitmapInfo = originalBitmapInfo switch (alphaInfo) { case .None: bitmapInfo = ~CGBitmapInfo.AlphaInfoMask bitmapInfo |= CGBitmapInfo(CGImageAlphaInfo.NoneSkipFirst.rawValue) case .PremultipliedFirst, .PremultipliedLast, .NoneSkipFirst, .NoneSkipLast: break case .Only, .Last, .First: return image } if let context = CGBitmapContextCreate(nil, CGImageGetWidth(imageRef), CGImageGetHeight(imageRef), CGImageGetBitsPerComponent(imageRef), 0 , colorSpace, bitmapInfo) { CGContextDrawImage(context, imageRect, imageRef) let decompressedImageRef = CGBitmapContextCreateImage(context) if let decompressedImage = UIImage(CGImage: decompressedImageRef, scale: image.scale, orientation: image.imageOrientation) { return decompressedImage } else { return image } } else { return image } }從 NSData 判斷圖片類型
要判斷圖片格式,可以依據不同格式開頭幾個字節的特徵,在 contentTypeForImageData(data: NSData) -> String? 方法裡實現了從 NSData 中獲取類型的邏輯:
func contentTypeForImageData(data: NSData) -> String? { var value : Int16 = 0 if data.length >= sizeof(Int16) { data.getBytes(&value, length:1) switch (value) { case 0xff: return "image/jpeg" case 0x89: return "image/png" case 0x47: return "image/gif" case 0x49: return "image/tiff" case 0x4D: return "image/tiff" case 0x52: if (data.length < 12) { return nil } if let temp = NSString(data: data.subdataWithRange(NSMakeRange(0, 12)), encoding: NSASCIIStringEncoding) { if (temp.hasPrefix("RIFF") && temp.hasSuffix("WEBP")) { return "image/webp" } } return nil default: return nil } } else { return nil } }之所以能這樣判斷,是因為不同圖片格式開頭的幾個字節都是獨一無二的,File magic numbers 裡有一份相對完整的對照表可供查閱。比如 jpeg 的前四個字節固定是 ff d8 ff e0。
Fetcher 的設計玩法
獲取圖片時統一通過 Fetcher 來完成,並根據任務性質區分是走服務器下載還是本地加載。
首先是 ImageFetcher 這個大基類,它封裝了一些公共的屬性與方法:
class ImageFetcher { typealias CompeltionClosure = (FetcherResult) -> Void let imageURL: NSURL init(imageURL: NSURL) { self.imageURL = imageURL } deinit { self.completion = nil } var cancelled = false var completion: CompeltionClosure? static func fetchImage(url: NSURL, completion: CompeltionClosure?) -> ImageFetcher { var fetcher: ImageFetcher if url.fileURL { fetcher = DiskImageFetcher(imageURL: url) } else { fetcher = RemoteImageFetcher(imageURL: url) } fetcher.completion = completion fetcher.startFetch() return fetcher } func cancelFetch() { self.cancelled = true } func startFetch() { fatalError("Subclass need to override this method called: \"startFetch\" ") } final func failedWithError(error: NSError) { } final func succeedWithData(imageData: NSData) { } }在 fetchImage 這個方法裡,通過 url.fileURL 判斷該走網絡請求還是本地請求,進而初始化不同的 fetcher。對於那些必须由子類實現的方法,用 fatalError 報錯來提醒;而對於絕不允許子類重寫的方法,則用 final 保護起來。比如請求成功後的回調方法 succeedWithData(imageData: NSData):
final func succeedWithData(imageData: NSData) { dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_HIGH, 0), { [weak self]() -> Void in if let strongSelf = self { var finalImage: UIImage! if let image = imageWithData(imageData) { finalImage = scaledImage(image) finalImage = decodedImageWithImage(finalImage) dispatch_main_async_safe { if !strongSelf.cancelled { if let completionClosure = strongSelf.completion { let result = FetcherResult.Success(image: finalImage, imageData: imageData) completionClosure(result) } } } } else { let error = NSError(domain: CHUN_ERROR_DOMAIN, code: 404, userInfo: [NSLocalizedDescriptionKey: "create Image with data failed"]) strongSelf.failedWithError(error) } } }) }無論是本地加載還是遠程獲取,最終拿到的都是 NSData,所以能在此統一處理。至於「取消」事件,其實並沒有真正中止下載任務,而是在下載成功後通過 strongSelf.cancelled 來判斷是否還要觸發成功回調。
接著分別看看本地加載和網絡獲取這兩部分。本地加載相對簡單,用 NSData(contentsOfURL: self.imageURL) 就能讀取圖片。網絡請求則基於 NSURLSession 實現,對 NSURLSession 不太熟悉的同學可以讀讀《從 NSURLConnection 到 NSURLSession》。
網絡請求成功後,做了如下幾件事:
檢查 self 是否還存活
檢查當前任務是否已被取消
檢查回調的 error 是否為空
取出 response 並確認狀態碼是否為 200
在一切正常的前提下,還進行了進一步校驗:
let expected = response.expectedContentLength var validateLengthOfData: Bool { if expected > -1 { if Int64(data!.length) >= expected { return true } else { return false } } return true } if validateLengthOfData { strongSelf.succeedWithData(data!) return } else { let error = NSError(domain: CHUN_ERROR_DOMAIN, code: response.statusCode, userInfo: [NSLocalizedDescriptionKey: "Received bytes are not fit with expected"]) strongSelf.failedWithError(error) return }核心目的是核對實際收到的數據大小是否與應有大小相符,並用 validateLengthOfData 這個計算屬性標記校驗結果。
緩存
所有圖片緩存都由 ImageCache 這個類統一打理。初始化時它新建了一個專門跑 IO 的 ioQueue 隊列,並用 NSCache 在內存中緩存圖片。NSCache 在 NSHipster 上被吐槽過,但影響不大,日常開發基本夠用。
系統事件的處理
在收到 UIApplicationDidEnterBackgroundNotification 通知時,會執行 backgroundCleanDisk 的清理:
private func backgroundCleanDisk() { let application = UIApplication.sharedApplication() var backgroundTask: UIBackgroundTaskIdentifier! backgroundTask = application.beginBackgroundTaskWithExpirationHandler { application.endBackgroundTask(backgroundTask) backgroundTask = UIBackgroundTaskInvalid } self.cleanDisk { application.endBackgroundTask(backgroundTask) backgroundTask = UIBackgroundTaskInvalid } }借助 beginBackgroundTaskWithExpirationHandler,App 退到後台後就能把本地的過期文件清理掉。
過期文件
判斷過期文件的關鍵在於下面這段:
let expirationDate = NSDate(timeIntervalSinceNow: ImageCache.defaultCacheMaxAge) let modificationDate = resourceValues[NSURLContentModificationDateKey] as! NSDate if modificationDate.laterDate(expirationDate).isEqualToDate(expirationDate) { ... }通過遍歷檢查所有過期文件,把它們收進 cacheFiles 數組,再統一刪除。
小結
讀完 Chun 這個項目,等於跟著走了一遍一個簡單圖片緩存庫的實現過程,涵蓋圖片加載與本地緩存兩大核心功能,並用 public class 把公共接口封裝對外暴露。過程中還領會了不少 Swift 小技巧,總結一句:Excited 嗯!