diff --git a/SwiftGifCommon/UIImage+Gif.swift b/SwiftGifCommon/UIImage+Gif.swift index b217ba5..ce85a4b 100755 --- a/SwiftGifCommon/UIImage+Gif.swift +++ b/SwiftGifCommon/UIImage+Gif.swift @@ -10,30 +10,54 @@ import UIKit import ImageIO extension UIImage { - + public class func gifWithData(data: NSData) -> UIImage? { + // Create source from data guard let source = CGImageSourceCreateWithData(data, nil) else { print("SwiftGif: Source for the image does not exist") return nil } + return UIImage.animatedImageWithSource(source) } - + + public class func gifWithURL(gifUrl:String) -> UIImage? { + // Validate URL + guard let bundleURL:NSURL? = NSURL(string: gifUrl) + else { + print("SwiftGif: This image named \"\(gifUrl)\" does not exist") + return nil + } + + // Validate data + guard let imageData = NSData(contentsOfURL: bundleURL!) else { + print("SwiftGif: Cannot turn image named \"\(gifUrl)\" into NSData") + return nil + } + + return gifWithData(imageData) + } + public class func gifWithName(name: String) -> UIImage? { - guard let bundleURL = NSBundle.mainBundle().URLForResource(name, withExtension: "gif") else { + // Check for existance of gif + guard let bundleURL = NSBundle.mainBundle() + .URLForResource(name, withExtension: "gif") else { print("SwiftGif: This image named \"\(name)\" does not exist") return nil } + + // Validate data guard let imageData = NSData(contentsOfURL: bundleURL) else { print("SwiftGif: Cannot turn image named \"\(name)\" into NSData") return nil } + return gifWithData(imageData) } - + class func delayForImageAtIndex(index: Int, source: CGImageSource!) -> Double { var delay = 0.1 - + // Get dictionaries let cfProperties = CGImageSourceCopyPropertiesAtIndex(source, index, nil) let gifProperties: CFDictionaryRef = unsafeBitCast( @@ -50,16 +74,16 @@ extension UIImage { delayObject = unsafeBitCast(CFDictionaryGetValue(gifProperties, unsafeAddressOf(kCGImagePropertyGIFDelayTime)), AnyObject.self) } - + delay = delayObject as! Double - + if delay < 0.1 { delay = 0.1 // Make sure they're not too fast } - + return delay } - + class func gcdForPair(var a: Int?, var _ b: Int?) -> Int { // Check if one of them is nil if b == nil || a == nil { @@ -71,19 +95,19 @@ extension UIImage { return 0 } } - + // Swap for modulo if a < b { let c = a a = b b = c } - + // Get greatest common divisor var rest: Int while true { rest = a! % b! - + if rest == 0 { return b! // Found it } else { @@ -92,70 +116,70 @@ extension UIImage { } } } - + class func gcdForArray(array: Array) -> Int { if array.isEmpty { return 1 } - + var gcd = array[0] - + for val in array { gcd = UIImage.gcdForPair(val, gcd) } - + return gcd } - + class func animatedImageWithSource(source: CGImageSource) -> UIImage? { let count = CGImageSourceGetCount(source) var images = [CGImageRef]() var delays = [Int]() - + // Fill arrays for i in 0..