swiftgifnsimageview

Display gif inside NSImageView - Swift 3 - Mac


I am trying to load and display a gif file inside a NSImageView but nothing appears when I run the project.

I have try to link the gif file with NSImageView using url, data or named, but it does not work.

 func applicationDidFinishLaunching(_ aNotification: Notification)
    {
 let url = Bundle.main.url(forResource: "RSynchro-Gif", withExtension: "gif")!
        let data = try! Data(contentsOf: url)
        gifBoutton.image = NSImage(data: data)
}

or

func applicationDidFinishLaunching(_ aNotification: Notification)
    {
        let url = Bundle.main.url(forResource: "RSynchro-Gif", withExtension: "gif")!
        gifBoutton.image = try! NSImage(data: Data(contentsOf: url))
    }

or

func applicationDidFinishLaunching(_ aNotification: Notification)
    {

       let icon = NSImage(named: NSImage.Name(rawValue: "RSynchro-Gif"))
       imageGif.image = icon
       imageGif.animates = true
    }

None of them works but if I replace the .gif file with a .png, it works. Anyone to show me the right way? Thanks.


Solution

  • (See the edit to my answer below. My initial answer was outdated and therefore wrong.)

    I don't believe there is native support for GIF image type in Mac OS. (I know for a fact there isn't in iOS, where I do most of my work these days, and am fairly sure the same holds true for Mac OS. I know Mac OS didn't support GIF as of about 3 years ago.)

    EDIT:

    Apparently I'm wrong. It looks like you can load the first frame of a GIF image if you put the image in your app's bundle directly rather than into your assets catalog. If you create an image set in your asset catalog and drag a GIF into that it appears to work in Xcode but the image doesn't load. (I tried it for both a Mac app and an iOS app and the results are the same.)