0

Twitter now supports posting animated gifs. see: https://twitter.com/Support/status/479307198901026816 However I've been trying to post an animated gif to twitter using the SLComposeViewController but the gif gets flattened to a single frame.

NSData *data = [NSData dataWithContentsOfFile:self.filepath];    
UIImage *gif = [UIImage imageWithData:data];

SLComposeViewController *sheet = [SLComposeViewController composeViewControllerForServiceType:serviceType];
[sheet setInitialText:[NSString stringWithFormat:@"Just created a Gif"]];
[sheet addImage:gif];
[self presentViewController:sheet animated:YES completion:nil];
Ramin Afshar
  • 989
  • 2
  • 18
  • 34
  • Have you tried `+(UIImage *)animatedImageWithImages:(NSArray *)images duration:(NSTimeInterval)duration` to create your `UIImage`. – Milo Jul 21 '14 at 20:24

2 Answers2

2

You can use SLRequest, a lower-level way of accessing the API through the Twitter API itself, to accomplish this.

You're going to have to wait until Apple implements support for animated GIFs if you want to use SLComposeViewController - this likely isn't something that you're going to be able to fix in your code.

Undo
  • 25,519
  • 37
  • 106
  • 129
  • SLSRequest did the trick. https://dev.twitter.com/docs/ios/posting-images-using-twrequest – Ramin Afshar Jul 21 '14 at 21:25
  • For those who are looking for the codes on how to do this on SLRequest, read here: http://xcodenoobies.blogspot.my/2016/01/how-to-using-slrequest-to-upload-image.html – GeneCode Jan 14 '16 at 05:54
-1

Maybe you can try to create your UIImage from the individual frames as UIImage supports this through +(UIImage *)animatedImageWithImages:(NSArray *)images duration:(NSTimeInterval)duration.

To get the frames from your NSData you can do this, but first make sure to import <ImageIO/ImageIO.h> and link your binary to that framework.

NSData *data = [NSData dataWithContentsOfFile:self.filepath];

NSMutableArray *frames = nil;
CGImageSourceRef sourceRef = CGImageSourceCreateWithData((__bridge CFDataRef)data, NULL);
if (sourceRef) {
     size_t frameCount = CGImageSourceGetCount(sourceRef);
     frames = [NSMutableArray arrayWithCapacity:frameCount];
     for (size_t i = 0; i < frameCount; i++) {
         CGImageRef image = CGImageSourceCreateImageAtIndex(sourceRef, i, NULL);
         if (image) {
             [frames addObject:[UIImage imageWithCGImage:image]];
             CGImageRelease(image);
         }   
     }   
     CFRelease(sourceRef);
}

Then after you have your frames you can create an animated UIImage like so:

UIImage *animatedImage = [UIImage animatedImageWithImages:frames
                                   duration: frames.count / 30.0];

Note this is assuming your gif is playing back at 30 frames per second. You can change this by changing 30 to your desired frame rate. Now you should be able to post like this:

[sheet addImage:animatedImage].

Milo
  • 5,041
  • 7
  • 33
  • 59