Skip to content

Instantly share code, notes, and snippets.

@gboyegadada
Last active January 13, 2024 03:01
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gboyegadada/a6c76f674958726716782d156c032d9e to your computer and use it in GitHub Desktop.
Save gboyegadada/a6c76f674958726716782d156c032d9e to your computer and use it in GitHub Desktop.
Simple GIF player for Swift. Tested on macOS but should work with iOS too (remember to switch NSImage to UIImage in the example)
//
// ExampleView.swift
//
// Created by Gboyega Dada on 13/01/2024.
//
import SwiftUI
struct ExampleView: View {
var src: URL
var previewURL: URL?
var width: CGFloat = 200.0 // default
@State var player: GIFPlayer? = nil
@State var preview: Image? = nil
var body: some View {
ZStack(alignment: .top) {
if let preview {
preview
.resizable()
.aspectRatio(contentMode: .fit)
.frame(minWidth: width, maxWidth: width, alignment: .center)
.cornerRadius(30)
.clipped()
}
if player?.stopped == false, let image = player?.image {
Image(image, scale: 1.0, orientation: .up, label: Text(""))
.resizable()
.aspectRatio(contentMode: .fit)
.frame(minWidth: width, maxWidth: width, alignment: .center)
.cornerRadius(30)
.clipped()
}
} /// ZStack
.frame(minWidth: width, maxWidth: width)
.background(Color.clear)
.task {
preview = await loadPreview(previewURL)
player = .init(src)
await player?.play()
}
.onDisappear {
player?.stop()
player = nil
preview = nil
}
}
func loadPreview(_ url: URL?) async -> Image? {
guard let url, let image = NSImage(contentsOf: url) else { return nil }
return Image(nsImage: image)
}
}
//
// GIFPlayer.swift
//
// Created by Gboyega Dada on 10/01/2024.
//
import Foundation
import ImageIO
@Observable final class GIFPlayer {
private(set) var image: CGImage?
private(set) var stopped: Bool = true
public var src: URL
private let defaultLoopCount: Int = 5
private var timeout: Timeout = .init()
private func tick() {
guard !stopped else { return }
timeout.begin(in: 0.4) { [weak self] in self?.stopped = true }
}
init(_ url: URL) {
self.src = url
}
deinit {
stop()
}
func play(loopCount: Int? = nil, startIndex: Int? = nil) async {
guard stopped else { return }
stopped = false
guard startWithFrameHandler(loopCount: loopCount ?? defaultLoopCount, startIndex: startIndex ?? 0) == true
else {
print("debug GIFPlayer -- ⚠️ failed to animate image at url \(src.path)")
return
}
}
func stop() {
timeout.cancel()
stopped = true
}
}
extension GIFPlayer {
private func startWithFrameHandler(loopCount: Int, startIndex: Int) -> Bool {
let options: CFDictionary = [
kCGImageAnimationLoopCount as String : loopCount,
kCGImageAnimationStartIndex as String : startIndex
] as CFDictionary
let status: OSStatus = CGAnimateImageAtURLWithBlock(src as CFURL, options) { [weak self] _, image, isStopping in
guard let self else {
isStopping.pointee = true
return
}
self.tick()
self.image = image
isStopping.pointee = self.stopped
}
return status == noErr
}
}
//
// SpringLoader.swift
//
// Created by Gboyega Dada on 07/01/2024.
//
import Foundation
@Observable final class Timeout {
private var task: Task<Void, Never>? = nil
func begin(in seconds: TimeInterval = 1.4, perform: @escaping () -> Void) {
cancel()
task = Task(priority: .userInitiated) { [weak self] in
do {
try await Task.sleep(seconds: seconds)
await MainActor.run { [weak self] in
perform()
}
} catch {
// Cancel timeout
}
}
}
func cancel() {
task?.cancel()
task = nil
}
}
@gboyegadada
Copy link
Author

Not sure if this is an ideal way to check if the loops have completed (with a timeout). Seems there is no direct way to do it. But if you have a cleaner way, please share!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment