Swift版本的图片加载类

前端之家收集整理的这篇文章主要介绍了Swift版本的图片加载类前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

之前使用OC版本的,都是基于AFN而自行封装的类库,

现在写了一个swift版本的,很方便使用,在些开源出来。


首先是图片下载类:

//
//  HYBImageLoader.swift
//  OSChinaClient
//
//  Created by 黄仪标 on 15/3/5.
//  Copyright (c) 2015年 huangyibiao free edu. All rights reserved.
//

import Foundation
import UIKit

///
/// 图片下载类,使用NSCache作为缓存处理
///
/// 作者:黄仪标
///
/// Email: 632840804@qq.com
///
/// github:https://github.com/632840804
///
/// CSDN Blog: http://blog.csdn.net/woaifen3344/
///
/// Note:有任何可以,可以通过Email反馈,会在空闲时间处理,谢谢!
///
class HYBImageLoader {
  /// 缓存处理对象
  var cache = NSCache()
  
  ///
  /// 声明为单例
  ///
  class var sharedInstance : HYBImageLoader {
    struct Loader {
      static let instance = HYBImageLoader()
    }
    return Loader.instance
  }
  
  ///
  /// 加载图片
  ///
  /// url 图片请求地址
  ///
  /// completion 加载完成时的回调,不论是加载成功还是加载失败,都会回调
  ///            image 可空类型,为nil表示加载失败,不为nil,表示加载成功
  ///            isFromCache Bool类型,表示是否是从缓存中提取出来的图片
  func loadImage(url: String,completionHandler:(image: UIImage?,isFromCache: Bool) -> ()) {
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND,0),{()in
      var data: NSData? = self.cache.objectForKey(url.md5ForLoader) as? NSData
      
      if let goodData = data {
        let image = UIImage(data: goodData)
        dispatch_async(dispatch_get_main_queue(),{() in
          completionHandler(image: image,isFromCache: true)
        })
        return
      }
      
      var downloadTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: url)!,completionHandler: {(data: NSData!,response: NSURLResponse!,error: NSError!) -> Void in
        if (error != nil) {
          completionHandler(image: nil,isFromCache: false);
          return
        }
        
        if data != nil {
          let image = UIImage(data: data)
          self.cache.setObject(data,forKey: url.md5ForLoader)
          dispatch_async(dispatch_get_main_queue(),{() in
            completionHandler(image: image,isFromCache: false)
          })
          return
        }
        
      });
      downloadTask.resume()
    })
  }
}

///
/// String结构通用功能扩展
///
extension String {
  ///
  /// 获取自身md5加密后的字符串
  ///
  var md5ForLoader : String {
    let str = self.cStringUsingEncoding(NSUTF8StringEncoding)
    let strLen = CC_LONG(self.lengthOfBytesUsingEncoding(NSUTF8StringEncoding))
    let digestLen = Int(CC_MD5_DIGEST_LENGTH)
    let result = UnsafeMutablePointer<CUnsignedChar>.alloc(digestLen);
    
    CC_MD5(str!,strLen,result);
    
    var hash = NSMutableString();
    for i in 0 ..< digestLen {
      hash.appendFormat("%02x",result[i]);
    }
    result.destroy();
    
    return String(format: hash)
  }
}

接下来就是图片加载控件类:
//
//  HYBLoadingImageView.swift
//  OSChinaClient
//
//  Created by 黄仪标 on 15/3/5.
//  Copyright (c) 2015年 huangyibiao free edu. All rights reserved.
//

import Foundation
import UIKit

typealias HYBImageLoadingCompletion = (image: UIImage?) -> ();
typealias HYBImageCompletion = (image: UIImage?,isFromCache: Bool) -> ();

///
/// 图片加载控件,所有需要到网络加载的图片,都需要使用此控件操作
///
/// 作者:黄仪标
///
/// Email: 632840804@qq.com
///
/// github:https://github.com/632840804
///
/// CSDN Blog: http://blog.csdn.net/woaifen3344/
///
/// Note:有任何可以,可以通过Email反馈,会在空闲时间处理,谢谢!
///
class HYBLoadingImageView: UIImageView {
  override convenience init() {
    self.init(frame: CGRectZero);
  }
  
  override init(frame: CGRect) {
    super.init(frame: frame);
    
    self.clipsToBounds = true;
    self.layer.masksToBounds = true;
  }
  
  required init(coder aDecoder: NSCoder) {
    super.init(coder: aDecoder);
    
    self.clipsToBounds = true;
    self.layer.masksToBounds = true;
  }
  
  ///
  /// 是否将图片控件显示为圆形
  ///
  /// isCircle true表示显示为圆
  ///
  func isCircle(isCircle: Bool = false) {
      if isCircle == true {
        var width = min(self.frame.size.width,self.frame.size.height);
        self.frame = CGRectMake(self.frame.origin.x,self.frame.origin.y,width,width);
        self.layer.cornerRadius = width / 2;
      }
  }
  
  ///
  /// 加载图片
  ///
  /// url 图片请求地址
  ///
  func loadImage(url: String) {
    self.loadImage(url,holder: "");
  }
  
  ///
  /// 加载图片
  ///
  /// url 图片请求地址
  ///
  /// holder 占位图片名称
  ///
  func loadImage(url: String,holder: String) {
    self.loadImage(url,holder: holder,completion: nil);
  }
  
  ///
  /// 加载图片
  ///
  /// url 图片请求地址
  ///
  /// completion 图片加载完成时的回调闭包
  ///
  func loadImage(url: String,completion: HYBImageLoadingCompletion?) {
    self.loadImage(url,holder: "",completion: completion);
  }
  
  ///
  /// 加载图片
  ///
  /// url 图片请求地址
  ///
  /// holder 占位图片名称
  ///
  /// completion 图片加载完成时的回调闭包
  ///
  func loadImage(url: String,holder: String,completion: HYBImageLoadingCompletion?) {
    if !holder.isEmpty {
      self.image = UIImage(named: holder);
    }
    
    if url.isEmpty {
      completion?(image: nil);
      return;
    }
    
    HYBImageLoader.sharedInstance.loadImage(url,completionHandler: { (image,isFromCache) -> () in
      if image == nil { // 图片加载失败
        completion?(image: nil);
      } else {
        println(url);
        
        // 在图片加载成功后,如果处理添加图片显示的动画处理,如果在此处添加
        if !isFromCache {
          // 添加淡入淡出的动画效果
          let animation = CATransition();
          animation.duration = 0.65;
          animation.type = kCATransitionFade;
          animation.removedOnCompletion = true;
          self.layer.addAnimation(animation,forKey: "transition");
        }
        
        self.image = image;
        completion?(image: image);
      }
    });
  }
}

github下载地址: https://github.com/632840804/SwiftImageView/tree/master

猜你在找的Swift相关文章