Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Copy GIF to UIPasteboard

I'm trying to copy a GIF image to the UIPasteboard in swift, at the moment it only copies the static version of the image and seems to convert it to PNG looking at the file extension when I upload it somewhere.

Wondered if anyone had any idea how to achieve this? All other soltions I've found only seem to work when getting NSData from a URL rather than from an image in the bundle

like image 294
jackchmbrln Avatar asked Nov 12 '15 15:11

jackchmbrln


2 Answers

For anyone who ever encounters this problem I managed to find a solution

let url: NSURL = NSBundle.mainBundle().URLForResource("\(self.imageNames[indexPath.row])", withExtension: ".gif")!
let data: NSData = NSData(contentsOfURL: url)!
UIPasteboard.generalPasteboard().setData(data, forPasteboardType: "com.compuserve.gif")

As it turns out you do need to use a URL and extract the NSData of the GIF from that URL.

Here I am getting the URL of the GIF that is in my bundle, searching for it using the name and extension of the image. I am then setting the data in the pasteboard and bingo we have an animated GIF when pasting the result from the pasteboard

like image 167
jackchmbrln Avatar answered Nov 13 '22 00:11

jackchmbrln


It doesn't look like the image property on the pasteboard supports the GIF type.

The associated array of representation types is UIPasteboardTypeListImage, which includes types kUTTypePNG and kUTTypeJPEG.

You could probably do this using the NSData from the GIF though:

import MobileCoreServices

// ...

var image = UIImage(...)
let data = NSData(bytes: &image, length: sizeof(UIImage))
UIPasteboard.generalPasteboard().setData(data, forPasteboardType: kUTTypeGIF as String)) // com.compuserve.gif
like image 41
JAL Avatar answered Nov 12 '22 23:11

JAL