Skip to content

Instantly share code, notes, and snippets.

@westerlund
Created December 22, 2014 17:07
Show Gist options
  • Select an option

  • Save westerlund/eae8ec71cdac88be7c3a to your computer and use it in GitHub Desktop.

Select an option

Save westerlund/eae8ec71cdac88be7c3a to your computer and use it in GitHub Desktop.

Revisions

  1. westerlund created this gist Dec 22, 2014.
    24 changes: 24 additions & 0 deletions gif.swift
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,24 @@
    func createGIF(with images: [UIImage], loopCount: Int = 0, frameDelay: Double, callback: (data: NSData?, error: NSError?) -> ()) {
    let fileProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFLoopCount as String: loopCount]]
    let frameProperties = [kCGImagePropertyGIFDictionary as String: [kCGImagePropertyGIFDelayTime as String: frameDelay]]

    let documentsDirectory = NSTemporaryDirectory()
    let url = NSURL(fileURLWithPath: documentsDirectory)?.URLByAppendingPathComponent("animated.gif")

    if let url = url {
    let destination = CGImageDestinationCreateWithURL(url, kUTTypeGIF, UInt(images.count), nil)
    CGImageDestinationSetProperties(destination, fileProperties)

    for i in 0..<images.count {
    CGImageDestinationAddImage(destination, images[i].CGImage, frameProperties)
    }

    if CGImageDestinationFinalize(destination) {
    callback(data: NSData(contentsOfURL: url), error: nil)
    } else {
    callback(data: nil, error: NSError())
    }
    } else {
    callback(data: nil, error: NSError())
    }
    }