### Install SwiftyGif with Carthage Source: https://github.com/alexiscreuzot/swiftygif/blob/master/README.md Instructions for installing SwiftyGif using Carthage, a decentralized dependency manager for iOS, macOS, tvOS, and watchOS. ```shell github "kirualex/SwiftyGif" ``` -------------------------------- ### Install SwiftyGif with CocoaPods Source: https://github.com/alexiscreuzot/swiftygif/blob/master/README.md Instructions for installing SwiftyGif using CocoaPods, a dependency manager for Swift and Objective-C projects. ```ruby source 'https://github.com/CocoaPods/Specs.git' use_frameworks! pod 'SwiftyGif' ``` -------------------------------- ### Handle GIF Lifecycle with SwiftyGifDelegate Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Shows how to implement the SwiftyGifDelegate protocol to track playback events like start, loop completion, and stop, as well as handling remote GIF loading status. ```swift extension DelegateExampleViewController: SwiftyGifDelegate { func gifDidStart(sender: UIImageView) { print("GIF playback started") } func gifDidLoop(sender: UIImageView) { print("Completed loop") } func gifDidStop(sender: UIImageView) { print("GIF playback stopped") } func gifURLDidFinish(sender: UIImageView) { print("Remote GIF loaded successfully") } func gifURLDidFail(sender: UIImageView, url: URL, error: Error?) { print("Failed to load GIF") } } ``` -------------------------------- ### Install SwiftyGif with Swift Package Manager Source: https://github.com/alexiscreuzot/swiftygif/blob/master/README.md Instructions for installing SwiftyGif using Swift Package Manager, the official dependency manager for Swift. ```swift https://github.com/kirualex/SwiftyGif.git ``` -------------------------------- ### Control GIF Playback with SwiftyGif Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Provides methods to control GIF animation playback using SwiftyGif. This includes starting, stopping, and toggling animation, as well as navigating through individual frames and clearing the GIF from memory. It also shows how to retrieve frame information. ```swift import SwiftyGif class PlaybackControlViewController: UIViewController { @IBOutlet weak var gifImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() do { let gif = try UIImage(gifName: "animation.gif") gifImageView.setGifImage(gif, loopCount: -1) } catch { print("Failed to load GIF: \(error)") } } // Start/Stop playback @IBAction func playTapped(_ sender: UIButton) { gifImageView.startAnimatingGif() } @IBAction func pauseTapped(_ sender: UIButton) { gifImageView.stopAnimatingGif() } @IBAction func togglePlayback(_ sender: UIButton) { if gifImageView.isAnimatingGif() { gifImageView.stopAnimatingGif() sender.setTitle("Play", for: .normal) } else { gifImageView.startAnimatingGif() sender.setTitle("Pause", for: .normal) } } // Frame navigation @IBAction func nextFrameTapped(_ sender: UIButton) { gifImageView.stopAnimatingGif() gifImageView.showFrameForIndexDelta(1) // Move forward one frame } @IBAction func previousFrameTapped(_ sender: UIButton) { gifImageView.stopAnimatingGif() gifImageView.showFrameForIndexDelta(-1) // Move back one frame } @IBAction func jumpToFrame(_ sender: UIButton) { gifImageView.stopAnimatingGif() gifImageView.showFrameAtIndex(0) // Jump to first frame } // Get frame information func printFrameInfo() { if let gif = gifImageView.gifImage { print("Total frames: \(gif.framesCount())") print("Current frame: \(gifImageView.currentFrameIndex())") } } // Clear the GIF and release memory @IBAction func clearTapped(_ sender: UIButton) { gifImageView.clear() } } ``` -------------------------------- ### Playback Controls API Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Provides methods to control GIF animation playback, including starting, stopping, and navigating frames. ```APIDOC ## Playback Controls Provides methods to control GIF animation playback including start, stop, and frame navigation. ### Methods - `startAnimatingGif()`: Starts the GIF animation. - `stopAnimatingGif()`: Stops the GIF animation. - `isAnimatingGif()`: Returns `true` if the GIF is currently animating. - `showFrameForIndexDelta(_:)`: Moves to the next or previous frame. - `showFrameAtIndex(_:)`: Jumps to a specific frame index. - `clear()`: Clears the GIF and releases memory. ### Frame Information - `gifImage`: Accesses the `SwiftyGif` object for frame details. - `framesCount()`: Returns the total number of frames in the GIF. - `currentFrameIndex()`: Returns the index of the currently displayed frame. ### Request Example ```swift import SwiftyGif // Assuming gifImageView is an IBOutlet to a UIImageView // Load a GIF first, e.g., from a local resource: // do { // let gif = try UIImage(gifName: "animation.gif") // gifImageView.setGifImage(gif, loopCount: -1) // } catch { // print("Failed to load GIF: \(error)") // } // Control playback: // gifImageView.startAnimatingGif() // gifImageView.stopAnimatingGif() // gifImageView.showFrameForIndexDelta(1) // Next frame // gifImageView.showFrameAtIndex(0) // First frame // gifImageView.clear() ``` ### Response N/A (These are control methods, not network responses) ### Error Handling - `UIImage(gifName:)` can throw an error if the GIF fails to load. ``` -------------------------------- ### Control GIF Animation Playback in Swift Source: https://github.com/alexiscreuzot/swiftygif/blob/master/README.md Provides methods for controlling GIF animation playback on a UIImageView. Includes functions to start, stop, and show specific frames of the animation, as well as check its status and frame count. ```swift self.myImageView.startAnimatingGif() self.myImageView.stopAnimatingGif() self.myImageView.showFrameAtIndexDelta(delta: Int) self.myImageView.showFrameAtIndex(index: Int) // Utility methods: self.myImageView.isAnimatingGif() // Returns whether the gif is currently playing self.myImageView.gifImage!.framesCount() // Returns number of frames for this gif ``` -------------------------------- ### Load Remote GIFs with SwiftyGif Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Demonstrates how to download and display GIFs from URLs using SwiftyGif. It covers basic loading, using custom activity indicators, and handling completion callbacks with success and failure states. It also shows how to cancel a download task. ```swift import SwiftyGif class RemoteGifViewController: UIViewController { @IBOutlet weak var gifImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() loadRemoteGif() } func loadRemoteGif() { guard let url = URL(string: "https://media.giphy.com/media/example/giphy.gif") else { return } // Basic loading with default spinner gifImageView.setGifFromURL(url) // With custom activity indicator let loader = UIActivityIndicatorView(style: .large) loader.color = .white gifImageView.setGifFromURL(url, customLoader: loader) // With completion callback and error handling gifImageView.setGifFromURL( url, loopCount: -1, levelOfIntegrity: .default, showLoader: true ) { result in switch result { case .success(let data): print("GIF loaded successfully, size: \(data.count) bytes") case .failure(let error): print("Failed to load GIF: \(error)") } } } // Cancel download if needed func loadCancellableGif() { guard let url = URL(string: "https://example.com/large.gif") else { return } let task = gifImageView.setGifFromURL(url) { result in // Handle completion } // Cancel the download if needed DispatchQueue.main.asyncAfter(deadline: .now() + 2) { task?.cancel() } } } ``` -------------------------------- ### Implement SwiftyGif on macOS Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Demonstrates how to use SwiftyGif with NSImage and NSImageView on macOS. Includes memory management via SwiftyGifManager and delegate methods for tracking playback state. ```swift import SwiftyGif import AppKit class MacViewController: NSViewController, SwiftyGifDelegate { @IBOutlet weak var gifImageView: NSImageView! let gifManager = SwiftyGifManager(memoryLimit: 60) override func viewDidLoad() { super.viewDidLoad() do { let gif = try NSImage(gifName: "animation.gif", levelOfIntegrity: .default) gifImageView.setGifImage(gif, manager: gifManager, loopCount: -1) } catch { print("Failed to load GIF: \(error)") } } func loadRemoteGif() { guard let url = URL(string: "https://example.com/animation.gif") else { return } gifImageView.setGifFromURL(url, loopCount: -1) { result in switch result { case .success(let data): print("Loaded \(data.count) bytes") case .failure(let error): print("Error: \(error)") } } } func gifDidStart(sender: NSImageView) { print("GIF started") } } ``` -------------------------------- ### macOS Support (NSImage/NSImageView) Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Demonstrates how to use SwiftyGif with `NSImage` and `NSImageView` for macOS applications. ```APIDOC ## macOS Support (NSImage/NSImageView) SwiftyGif provides seamless integration with macOS applications using `NSImage` and `NSImageView`. ### Loading Local GIFs Load and display a local GIF using `NSImage` and `setGifImage`. **Endpoint:** N/A (Local file loading) **Parameters:** - `gifName` (String): The name of the GIF file in the project's resources. - `levelOfIntegrity` (GifLevelOfIntegrity): Quality setting for GIF decoding. - `manager` (SwiftyGifManager): An instance of `SwiftyGifManager` for memory management. - `loopCount` (Int): Number of loops. `-1` for infinite. **Example Usage:** ```swift let gifManager = SwiftyGifManager(memoryLimit: 60) let gif = try NSImage(gifName: "animation.gif", levelOfIntegrity: .default) gifImageView.setGifImage(gif, manager: gifManager, loopCount: -1) ``` ### Loading Remote GIFs Load GIFs directly from a URL into an `NSImageView`. **Endpoint:** N/A (Remote URL loading) **Parameters:** - `url` (URL): The URL of the remote GIF. - `loopCount` (Int): Number of loops. `-1` for infinite. - `completionHandler` (Result): Callback for success or failure. **Example Usage:** ```swift guard let url = URL(string: "https://example.com/animation.gif") else { return } gifImageView.setGifFromURL(url, loopCount: -1) { result in switch result { case .success(let data): print("Loaded \(data.count) bytes") case .failure(let error): print("Error: \(error)") } } ``` ### Playback Controls Control GIF playback using provided methods. **Methods:** - `startAnimatingGif()`: Starts or resumes animation. - `stopAnimatingGif()`: Stops animation. - `showFrameForIndexDelta(Int)`: Advances the animation by a specified frame delta. **Example Usage:** ```swift // In an IBAction for a Play/Pause button if gifImageView.isAnimatingGif() { gifImageView.stopAnimatingGif() } else { gifImageView.startAnimatingGif() } // In an IBAction for a Next Frame button gifImageView.showFrameForIndexDelta(1) ``` ### SwiftyGif Delegate Implement `SwiftyGifDelegate` to receive callbacks for animation events. **Delegate Methods:** - `gifDidStart(sender: NSImageView)` - `gifDidLoop(sender: NSImageView)` - `gifDidStop(sender: NSImageView)` **Example Implementation:** ```swift extension MacViewController: SwiftyGifDelegate { func gifDidStart(sender: NSImageView) { print("GIF started") } func gifDidLoop(sender: NSImageView) { print("GIF looped") } func gifDidStop(sender: NSImageView) { print("GIF stopped") } } ``` ``` -------------------------------- ### Initialize UIImage from Local GIF File Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Creates a UIImage object from a local GIF file. Supports quality control via `levelOfIntegrity` to balance performance and visual fidelity. Allows specifying a custom bundle for loading resources. ```swift import SwiftyGif // Load GIF from local file with default quality do { let gif = try UIImage(gifName: "animation.gif") print("Loaded GIF with \(gif.framesCount()) frames") } catch { print("Failed to load GIF: \(error)") } // Load GIF with reduced quality for better performance do { let gif = try UIImage(gifName: "animation.gif", levelOfIntegrity: 0.5) // Uses .lowForManyGifs preset - good for displaying multiple GIFs } catch { print("Failed to load GIF: \(error)") } // Load from specific bundle do { let customBundle = Bundle(for: MyClass.self) let gif = try UIImage(gifName: "animation.gif", bundle: customBundle) } catch { print("Failed to load GIF: \(error)") } // Available levelOfIntegrity presets: // .highestNoFrameSkipping (1.0) - Full quality, no frame skipping // .default (0.8) - Good balance of quality and performance // .lowForManyGifs (0.5) - For displaying several GIFs // .lowForTooManyGifs (0.2) - For many GIFs in a list // .superLowForSlideShow (0.1) - Minimal frames, slideshow effect ``` -------------------------------- ### Display GIF from Storyboard/NIB in Swift Source: https://github.com/alexiscreuzot/swiftygif/blob/master/README.md Shows how to set a GIF to a UIImageView directly from a nib or storyboard. It loads a GIF and uses the `setGifImage` method with a specified loop count. ```swift import SwiftyGif @IBOutlet var myImageView : UIImageView! ... let gif = try UIImage(gifName: "MyImage.gif") self.myImageView.setGifImage(gif, loopCount: -1) // Will loop forever ``` -------------------------------- ### Display GIF Programmatically in Swift Source: https://github.com/alexiscreuzot/swiftygif/blob/master/README.md Demonstrates how to load and display a GIF programmatically using SwiftyGif. It initializes a UIImage with a GIF name and then creates a UIImageView to display it, with options for loop count. ```swift import SwiftyGif do { let gif = try UIImage(gifName: "MyImage.gif") let imageview = UIImageView(gifImage: gif, loopCount: 3) // Will loop 3 times imageview.frame = view.bounds view.addSubview(imageview) } catch { print(error) } ``` -------------------------------- ### Remote GIF Loading API Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Demonstrates how to load GIFs from URLs, including options for custom loaders and completion callbacks. ```APIDOC ## Remote GIF Loading Downloads and displays GIFs from URLs with optional loading indicators and completion callbacks. ### Method `setGifFromURL(_:loopCount:levelOfIntegrity:showLoader:completion:)` ### Endpoint N/A (This is a library method, not a network endpoint) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```swift import SwiftyGif // Assuming gifImageView is an IBOutlet to a UIImageView // guard let url = URL(string: "https://media.giphy.com/media/example/giphy.gif") else { return } // gifImageView.setGifFromURL(url) ``` ### Response #### Success Response (200) GIF is displayed in the `UIImageView`. #### Response Example N/A ### Error Handling - `failure(Error)`: Indicates an error during GIF loading. ### Additional Methods - `setGifFromURL(_:customLoader:)`: Loads GIF with a custom activity indicator. - `setGifFromURL(_:)`: Loads GIF with a default spinner. - `setGifFromURL(_:loopCount:levelOfIntegrity:showLoader:completion:)`: Loads GIF with advanced options. - `setGifFromURL(_:)` (returns `URLSessionTask?`): Loads GIF and returns a task that can be cancelled. ### Cancel Download - `task?.cancel()`: Cancels an ongoing GIF download task. ``` -------------------------------- ### Implement SwiftyGifDelegate in a UIViewController Source: https://github.com/alexiscreuzot/swiftygif/blob/master/README.md This snippet demonstrates how to assign a delegate to a UIImageView and implement the required SwiftyGifDelegate methods to track the lifecycle of a GIF image. ```swift override func viewDidLoad() { super.viewDidLoad() self.imageView.delegate = self } extension MyController : SwiftyGifDelegate { func gifURLDidFinish(sender: UIImageView) { print("gifURLDidFinish") } func gifURLDidFail(sender: UIImageView) { print("gifURLDidFail") } func gifDidStart(sender: UIImageView) { print("gifDidStart") } func gifDidLoop(sender: UIImageView) { print("gifDidLoop") } func gifDidStop(sender: UIImageView) { print("gifDidStop") } } ``` -------------------------------- ### Initialize UIImage from GIF Data Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Creates a UIImage object from raw GIF data, suitable for GIFs loaded from network responses or databases. Allows quality control using `levelOfIntegrity`. ```swift import SwiftyGif // Load GIF from Data func loadGifFromData(_ gifData: Data) { do { let gif = try UIImage(gifData: gifData, levelOfIntegrity: .default) print("Loaded GIF with \(gif.framesCount()) frames") print("Estimated size: \(gif.imageSize ?? 0) MB") } catch { print("Failed to parse GIF data: \(error)") } } // Example: Loading from file manually if let url = Bundle.main.url(forResource: "animation", withExtension: "gif"), let data = try? Data(contentsOf: url) { do { let gif = try UIImage(gifData: data) // Use the gif image } catch { print("Invalid GIF data") } } ``` -------------------------------- ### SwiftUI Integration Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Provides `UIViewRepresentable` wrappers for using SwiftyGif with local and remote GIFs within SwiftUI views. ```APIDOC ## SwiftUI Integration This section details how to integrate SwiftyGif into SwiftUI applications using `UIViewRepresentable` wrappers. ### Local GIF Integration Use the `GifImageView` struct to display GIFs stored locally in your project's assets. **Parameters:** - `gifName` (String): The name of the GIF file (without extension). - `loopCount` (Int): The number of times the GIF should loop. `-1` for infinite loop. - `levelOfIntegrity` (GifLevelOfIntegrity): Controls the GIF decoding quality and performance. Defaults to `.default`. **Example Usage:** ```swift GifImageView(gifName: "animation.gif", loopCount: -1) .frame(width: 200, height: 200) ``` ### Remote GIF Integration Use the `RemoteGifView` struct to display GIFs from a remote URL. **Parameters:** - `url` (URL): The URL of the remote GIF. - `loopCount` (Int): The number of times the GIF should loop. `-1` for infinite loop. **Example Usage:** ```swift if let url = URL(string: "https://media.giphy.com/media/example/giphy.gif") { RemoteGifView(url: url) .frame(width: 200, height: 200) } ``` ### Advanced Usage (Quality Settings) Adjust `levelOfIntegrity` for performance-critical scenarios. **Example Usage:** ```swift GifImageView( gifName: "large-animation.gif", loopCount: 3, levelOfIntegrity: .lowForManyGifs ) .frame(width: 150, height: 150) ``` ``` -------------------------------- ### Display Remote GIF with Custom Loader in Swift Source: https://github.com/alexiscreuzot/swiftygif/blob/master/README.md Illustrates how to load a GIF from a URL and display it in a UIImageView. It allows for a custom loader view to be shown while the GIF is being downloaded. ```swift import SwiftyGif let url = URL(string: "...") let loader = UIActivityIndicatorView(style: .white) cell.gifImageView.setGifFromURL(url, customLoader: loader) ``` -------------------------------- ### Load GIF with Level of Integrity in Swift Source: https://github.com/alexiscreuzot/swiftygif/blob/master/README.md Demonstrates how to load a GIF with a specified level of integrity, which affects frame skipping to optimize CPU and memory usage. Lower values allow more frame skipping. ```swift import SwiftyGif do { let gif = try UIImage(gifName: "MyImage.gif", levelOfIntegrity:0.5) } catch { print(error) } ``` -------------------------------- ### Manage GIF Memory with SwiftyGifManager Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Demonstrates how to use SwiftyGifManager to control memory usage for multiple GIFs in a UITableView and how to use the default manager for simple cases. It includes manual memory clearing to optimize performance. ```swift import SwiftyGif class GifListViewController: UIViewController, UITableViewDataSource { @IBOutlet weak var tableView: UITableView! let gifManager = SwiftyGifManager(memoryLimit: 100) let gifNames = ["gif1.gif", "gif2.gif", "gif3.gif", "gif4.gif"] func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell { let cell = tableView.dequeueReusableCell(withIdentifier: "GifCell", for: indexPath) if let gifImageView = cell.viewWithTag(100) as? UIImageView { do { let gif = try UIImage(gifName: gifNames[indexPath.row], levelOfIntegrity: .lowForManyGifs) gifImageView.setGifImage(gif, manager: gifManager, loopCount: -1) } catch { gifImageView.clear() } } return cell } override func viewWillDisappear(_ animated: Bool) { super.viewWillDisappear(animated) gifManager.clear() } } ``` -------------------------------- ### Integrate SwiftyGif in SwiftUI Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Wraps UIImageView functionality into SwiftUI views using UIViewRepresentable. Supports both local file loading and remote URL fetching with configurable loop counts and integrity levels. ```swift import SwiftUI import SwiftyGif struct GifImageView: UIViewRepresentable { let gifName: String var loopCount: Int = -1 var levelOfIntegrity: GifLevelOfIntegrity = .default func makeUIView(context: Context) -> UIImageView { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView } func updateUIView(_ uiView: UIImageView, context: Context) { do { let gif = try UIImage(gifName: gifName, levelOfIntegrity: levelOfIntegrity) uiView.setGifImage(gif, loopCount: loopCount) } catch { print("Failed to load GIF: \(error)") } } } struct RemoteGifView: UIViewRepresentable { let url: URL var loopCount: Int = -1 func makeUIView(context: Context) -> UIImageView { let imageView = UIImageView() imageView.contentMode = .scaleAspectFit return imageView } func updateUIView(_ uiView: UIImageView, context: Context) { uiView.setGifFromURL(url, loopCount: loopCount) } } ``` -------------------------------- ### Display GIF in UIImageView Source: https://context7.com/alexiscreuzot/swiftygif/llms.txt Configures a UIImageView to display an animated GIF. Supports setting a specific loop count, from infinite (-1) to a fixed number of repetitions. Can also use `setImage` for automatic GIF detection. ```swift import SwiftyGif // Programmatic creation with infinite loop do { let gif = try UIImage(gifName: "animation.gif") let imageView = UIImageView(gifImage: gif, loopCount: -1) imageView.frame = CGRect(x: 0, y: 0, width: 200, height: 200) view.addSubview(imageView) } catch { print("Failed to load GIF: \(error)") } // Set GIF on existing UIImageView (e.g., from Storyboard) class ViewController: UIViewController { @IBOutlet weak var gifImageView: UIImageView! override func viewDidLoad() { super.viewDidLoad() do { let gif = try UIImage(gifName: "animation.gif") gifImageView.setGifImage(gif, loopCount: 3) // Loop 3 times then stop } catch { print("Failed to load GIF: \(error)") } } } // Using setImage for automatic GIF detection do { let image = try UIImage(imageName: "animation.gif") imageView.setImage(image, loopCount: -1) // Automatically handles GIF vs static images } catch { print("Failed to load image: \(error)") } ``` -------------------------------- ### SwiftUI UIViewRepresentable for GIF Display Source: https://github.com/alexiscreuzot/swiftygif/blob/master/README.md Provides a SwiftUI UIViewRepresentable struct to integrate SwiftyGif's UIImageView functionality into SwiftUI views. It allows displaying GIFs from a URL and updating them. ```swift import SwiftUI import SwiftyGif struct AnimatedGifView: UIViewRepresentable { @Binding var url: URL func makeUIView(context: Context) -> UIImageView { let imageView = UIImageView(gifURL: self.url) imageView.contentMode = .scaleAspectFit return imageView } func updateUIView(_ uiView: UIImageView, context: Context) { uiView.setGifFromURL(self.url) } } // Usage: // AnimatedGifView(url: Binding(get: { myModel.gif.url }, set: { _ in })) ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.