UIImageView UIButtont网络图片加载

在加载UIImageView UIButtont网络图片中常常采用第三方然而api过期就会到处去更改加载,下面采用URLSession写了一个类扩展,刚学Swift不是很熟请大神们指点欢迎多交流

//
// ImageViewExtension.swift
//
// ImageHelper
//
// Created by yyj on 2020/03/1.
// Copyright © 2020 apple. All rights reserved.
//

import Foundation
import UIKit
import QuartzCore

public extension UIImageView {

/**
 通过URL下载请求返回UIImage
 
 - Parameter url: 图片地址
 - Parameter placeholder: 默认image.
 - Parameter fadeIn: 显示效果.
 - Parameter closure: 闭包返回image
 
 - Returns A new image
 */
func imageFromURL(_ url: String, placeholder: UIImage, fadeIn: Bool = true, shouldCacheImage: Bool = true, closure: ((_ image: UIImage?) -> ())? = nil)
{
    self.image = UIImage.image(fromURL: url, placeholder: placeholder, shouldCacheImage: shouldCacheImage) {
        (image: UIImage?) in
        if image == nil {
            return
        }
        self.image = image
        if fadeIn {
            let transition = CATransition()
            transition.duration = 0.5
            transition.timingFunction = CAMediaTimingFunction(name: CAMediaTimingFunctionName.easeInEaseOut)
            transition.type = CATransitionType.fade
            self.layer.add(transition, forKey: nil)
        }
        closure?(image)
   	 }
 }


}

public extension UIButton {
/**
通过URL请求加载

- Parameter url: 图片地址
- Parameter placeholder: 默认image.
- Parameter shouldCacheImage: 是否缓存数据 默认是.
- Parameter state: 状态

*/
func imageFromURL(_ url: String, placeholder: UIImage, shouldCacheImage: Bool = true, for state: UIControl.State)
{
   func imageFromURL(_ url: String, placeholderImage: UIImage, shouldCacheImage: Bool = true, for state: UIControl.State)
{
    if url.isEmpty || url.count == 0 {
        self.setImage(placeholderImage, for: state)
    }else {
        if shouldCacheImage {
            if let image = UIImage.shared.object(forKey: url as AnyObject) as? UIImage {
                DispatchQueue.main.sync {
                    self.setImage(image, for: state)
                }
            }
        }
        // Fetch Image
        let session = URLSession(configuration: URLSessionConfiguration.default)
        if let nsURL = URL(string: url) {
            session.dataTask(with: nsURL, completionHandler: { (data, response, error) -> Void in
                if (error != nil) {
                    DispatchQueue.main.sync {
                        self.setImage(placeholderImage, for: state)
                    }
                }
                if let data = data, let image = UIImage(data: data) {
                    if shouldCacheImage {
                        UIImage.shared.setObject(image, forKey: url as AnyObject)
                    }
                    DispatchQueue.main.sync {
                        self.setImage(image, for: state)
                    }
                }
                session.finishTasksAndInvalidate()
            }).resume()
        }
    }
 }    
}

上面UIImageView加载image通过下面请求

//
// ImageHelper.swift
//
// ImageHelper
//
// Created by yyj on 2020/03/1.
// Copyright © 2020 apple. All rights reserved.
//

import Foundation
import UIKit

public extension UIImage {

/**
 A singleton shared NSURL cache used for images from URL
 */
static var shared: NSCache<AnyObject, AnyObject>! {
    struct StaticSharedCache {
        static var shared: NSCache<AnyObject, AnyObject>? = NSCache()
    }
    
    return StaticSharedCache.shared!
}

// MARK: Image From URL

/**
 Creates a new image from a URL with optional caching. If cached, the cached image is returned. Otherwise, a place holder is used until the image from web is returned by the closure.
 
 - Parameter url: The image URL.
 - Parameter placeholder: The placeholder image.
 - Parameter shouldCacheImage: Weather or not we should cache the NSURL response (default: true)
 - Parameter closure: Returns the image from the web the first time is fetched.
 
 - Returns A new image
 */
class func image(fromURL url: String, placeholder: UIImage, shouldCacheImage: Bool = true, closure: @escaping (_ image: UIImage?) -> ()) -> UIImage? {
    // From Cache
    if shouldCacheImage {
        if let image = UIImage.shared.object(forKey: url as AnyObject) as? UIImage {
            closure(nil)
            return image
        }
    }
    // Fetch Image
    let session = URLSession(configuration: URLSessionConfiguration.default)
    if let nsURL = URL(string: url) {
        session.dataTask(with: nsURL, completionHandler: { (data, response, error) -> Void in
            if (error != nil) {
                DispatchQueue.main.async {
                    closure(nil)
                }
            }
            if let data = data, let image = UIImage(data: data) {
                if shouldCacheImage {
                    UIImage.shared.setObject(image, forKey: url as AnyObject)
                }
                DispatchQueue.main.async {
                    closure(image)
                }
            }
            session.finishTasksAndInvalidate()
        }).resume()
    }
    return placeholder
 }
}
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值