Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to show gif into UIImageView in Swift?

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!

like image 948
user3745888 Avatar asked Jun 30 '14 07:06

user3745888


People also ask

What is UIImage?

An object that manages image data in your app.


1 Answers

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()
like image 79
Markus Rautopuro Avatar answered Oct 04 '22 16:10

Markus Rautopuro