Skip to content

Instantly share code, notes, and snippets.

@KrisYu
Created February 12, 2018 16:11
Show Gist options
  • Save KrisYu/1de008769dfe0b69c9343f0a4536ce95 to your computer and use it in GitHub Desktop.
Save KrisYu/1de008769dfe0b69c9343f0a4536ce95 to your computer and use it in GitHub Desktop.
// 📢名字:放在NSNotificationExtension.swift中,作为广播名字
extension NSNotification.Name {
static let BLDownloadImage = Notification.Name("BLDownloadImageNotification")
}
// 📢发送:放在 AlbumView.swift中
init(frame: CGRect, coverUrl: String) {
super.init(frame: frame)
commonInit()
// 发送出广播
NotificationCenter.default.post(name: .BLDownloadImage, object: self, userInfo: ["imageView" : coverImageView, "coverUrl": coverUrl])
}
// 📢接收:放在LibraryAPI.swift中
// 一旦开始init,便接收广播,接收到广播之后调用的方法是downloadImage(with:)
private init() {
NotificationCenter.default.addObserver(self, selector: #selector(downloadImage(with:)), name: .BLDownloadImage, object: nil)
}
// 之前post广播的时候就把一些消息放进了userInfo这个字典里
@objc func downloadImage(with notification: Notification) {
guard let userInfo = notification.userInfo,
let imageView = userInfo["imageView"] as? UIImageView,
let coverUrl = userInfo["coverUrl"] as? String,
let filename = URL(string: coverUrl)?.lastPathComponent else {
return
}
// 调用persistencyManager的 static method
// 如果我们已经在cache中有了这张image,我们就直接调用缓存的
if let savedImage = persistencyManager.getImage(with: filename) {
imageView.image = savedImage
return
}
// 否则我们用gcd先下载这张照片,然后让他显示到imageView中,再缓存它
DispatchQueue.global().async {
let downloadedImage = self.httpClient.downloadImage(coverUrl) ?? UIImage()
DispatchQueue.main.async {
imageView.image = downloadedImage
self.persistencyManager.saveImage(downloadedImage, filename: filename)
}
}
}
// 辅助方法
// PersistencyManager.swift中
// 找到Cache directory
private var cache: URL {
return FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask)[0]
}
// 存
func saveImage(_ image: UIImage, filename: String) {
let url = cache.appendingPathComponent(filename)
guard let data = UIImagePNGRepresentation(image) else {
return
}
try? data.write(to: url)
}
// 取
func getImage(with filename: String) -> UIImage? {
let url = cache.appendingPathComponent(filename)
guard let data = try? Data(contentsOf: url) else {
return nil
}
return UIImage(data: data)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment