代码改变世界

swift 异步加载图片(第三方框架ImageLoader)

2016-01-26 14:33  甘雨路  阅读(1104)  评论(0编辑  收藏  举报
import UIKit

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?


    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {
        self.window = UIWindow(frame: UIScreen.mainScreen().bounds)
        // Override point for customization after application launch.
        self.window!.backgroundColor = UIColor.whiteColor()
        
        self.window!.rootViewController = RootViewController();
        
        self.window!.makeKeyAndVisible()
        return true
    }
}

 

import UIKit

class RootViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        
        let imageView = UIImageView.init(frame: UIScreen.mainScreen().bounds);
        imageView.backgroundColor = UIColor.greenColor()
        self.view.addSubview(imageView)
        
        let path:String = "http://pic2.ooopic.com/11/86/60/84bOOOPIC13.jpg"
        //异步加载图片(第三方框架)
        ImageLoader.sharedLoader.imageForUrl(path) { (image, url) -> () in
            imageView.image = image
        }
    }
}

 

import UIKit
import Foundation


class ImageLoader {
    
    let cache = NSCache()

    class var sharedLoader : ImageLoader {
    struct Static {
        static let instance : ImageLoader = ImageLoader()
        }
        return Static.instance
    }
    
	func imageForUrl(urlString: String, completionHandler:(image: UIImage?, url: String) -> ()) {
		dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_BACKGROUND, 0), {()in
			let data: NSData? = self.cache.objectForKey(urlString) as? NSData
			
			if let goodData = data {
				let image = UIImage(data: goodData)
				dispatch_async(dispatch_get_main_queue(), {() in
					completionHandler(image: image, url: urlString)
				})
				return
			}
			
			let downloadTask: NSURLSessionDataTask = NSURLSession.sharedSession().dataTaskWithURL(NSURL(string: urlString)!, completionHandler: {(data: NSData?, response: NSURLResponse?, error: NSError?) -> Void in
				if (error != nil) {
					completionHandler(image: nil, url: urlString)
					return
				}
				
				if let data = data {
					let image = UIImage(data: data)
					self.cache.setObject(data, forKey: urlString)
					dispatch_async(dispatch_get_main_queue(), {() in
						completionHandler(image: image, url: urlString)
					})
					return
				}
				
			})
			downloadTask.resume()
		})
		
	}
}