5

I want use a gif in UIImageView, but I can't. My code is:

- (void)viewDidLoad {
    [super viewDidLoad];

    NSURL *url = [[NSBundle mainBundle] URLForResource:@"test" withExtension:@"gif"];
    UIImage *testImage = [UIImage animatedImageWithAnimatedGIFData:[NSData dataWithContentsOfURL:url]];
    self.dataImageView.animationImages = testImage.images;
    self.dataImageView.animationDuration = testImage.duration;
    self.dataImageView.animationRepeatCount = 1;
    self.dataImageView.image = testImage.images.lastObject;
    [self.dataImageView startAnimating];
}

Swift:

var url : NSURL = NSBundle.mainBundle().URLForResource("MAES", withExtension: "gif")

In objective C I had animatedImageWithAnimatedGIFData but in swift I don't know how call this or if not exists..

Thanks!

Meet Doshi
  • 4,241
  • 10
  • 40
  • 81
user3745888
  • 6,143
  • 15
  • 48
  • 97

1 Answers1

12

I assume you're using https://github.com/mayoff/uiimage-from-animated-gif for +UIImage animatedImageWithAnimatedGIFData: and the source code is in Objective-C.

You'll need to first import your Objective-C headers into Swift. Using Swift with Cocoa and Objective-C explains how to do this:

To import a set of Objective-C files in the same framework target as your Swift code, you’ll need to import those files into the Objective-C umbrella header for the framework.

To import Objective-C code into Swift from the same framework

  1. Under Build Settings, in Packaging, make sure the Defines Module setting for that framework target is set to Yes.
  2. In your umbrella header file, import every Objective-C header you want to expose to Swift. For example:

    #import "UIImage+animatedGIF.h"

You can then setup your testImage as follows:

var testImage = UIImage.animatedImageWithAnimatedGIFData(
    NSData.dataWithContentsOfURL(url))
self.dataImageView.animationImages = testImage.images
self.dataImageView.animationDuration = testImage.duration
self.dataImageView.animationRepeatCount = 1
self.dataImageView.image = testImage.images.lastObject
self.dataImageView.startAnimating()
Markus Rautopuro
  • 7,997
  • 6
  • 47
  • 60
  • Great! Thanks! It's ok. But I have other question, there are other form to show a gif directly without IImage+animatedGIF? – user3745888 Jun 30 '14 at 09:01
  • UIImage doesn't support _animated_ GIFs, but you can use still GIF images just like any other image (`UIImage(named: "image.gif")`). However, if you can split your animated GIF into separate still image GIFs, you're able to load them to UIImage animation like this: http://stackoverflow.com/a/2578648/2155985 – Markus Rautopuro Jun 30 '14 at 09:23