调用方式:
cell.imgView.sin_setImageWithUrl(url: "图片链接", placeholderImage: #imageLiteral(resourceName: "user_icon12"))
实现代码:
//
// DownLoadManager.swift
// QueueLoadImg
//
// Created by 郑东喜 on 2018/5/19.
// Copyright © 2018年 郑东喜. All rights reserved.
//
import UIKit
extension UIImageView {
/// 下载图片链接
///
/// - Parameter url: 图片链接
func sin_setImageWithUrl(url:String) {
sin_setImageWithUrl(url: url, placeholderImage: UIImage())
}
/// 下载图片链接
/// - Parameter placeholderImage: 占位图
/// - Parameter url: 图片链接
func sin_setImageWithUrl(url:String,placeholderImage:UIImage) {
self.image = placeholderImage
SINImageDownloaderManager.shared.downloadImage(url: url) {[weak self] (image) in
self?.image = image
}
}
}
extension String {
func cacheDir() -> String {
let cachePath = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.cachesDirectory, FileManager.SearchPathDomainMask.userDomainMask, true).last!
let filePath = (cachePath as NSString).appendingPathComponent((self as NSString).lastPathComponent)
return filePath
}
}
class SINImageDownloaderManager {
// 单粒
static let shared = SINImageDownloaderManager()
// 内存缓存图片,根据图片操作
var cacheImages:Dictionary<String, Any> = [:]
// 保存回调闭包
var completionDict = [String:(image:UIImage) -> Void]()
// 发现了swift的bug,当定义闭包时, var completion = (image:UIImage) -> Void(),这种写法到赋值后极易引发xcode代码颜色变黑,久不变回,望大神指出这种写法的错误。
// 队列
var queue:OperationQueue = {
let queue = OperationQueue.init()
queue.maxConcurrentOperationCount = 3
return queue
}()
func downloadImage(url:String,completion:@escaping (_ image:UIImage)->Void) {
completionDict[url] = completion
// 从内存缓存中取图片
let cacheImage = cacheImages[url] as! UIImage?
if cacheImage != nil {
if completionDict[url] != nil {
completionDict[url]!(cacheImage!)
return
}
}
// 从沙盒cache中获取图片
let cachePath = url.cacheDir()
print(cachePath)
let sanboxData = NSData.init(contentsOfFile: cachePath)
if (sanboxData != nil) {
let sandboxImage = UIImage.init(data: sanboxData! as Data)
// 保存到内存缓存
cacheImages[url] = sandboxImage
// 回调
if completionDict[url] != nil {
completionDict[url]!(sandboxImage!)
return
}
}
// 内存和沙盒中均没有图片,开始下载
queue.addOperation {
if let _url = URL.init(string: url) {
let downloadData = NSData.init(contentsOf: _url)
if downloadData != nil {
let downloadImage = UIImage.init(data: downloadData! as Data)
// 回主线程
OperationQueue.main.addOperation {
// 回调
if self.completionDict[url] != nil && downloadImage != nil {
self.completionDict[url]!(downloadImage!)
}
// 保存到内存
self.cacheImages[url] = downloadImage
// 保存到沙盒
downloadData?.write(to: URL.init(fileURLWithPath: cachePath), atomically: true)
}
}
}
}
}
}