### Initialize Git Submodule for Manual Installation Source: https://github.com/alamofire/alamofireimage/blob/master/docs/index.html Commands to initialize a git repository and add AlamofireImage as a submodule for manual integration. ```bash git init git submodule add https://github.com/Alamofire/AlamofireImage.git ``` -------------------------------- ### Swift: Dynamic Image Filters with AlamofireImage Source: https://context7.com/alamofire/alamofireimage/llms.txt Explains how to create custom image filters using closures for flexible and reusable transformations. Provides examples of creating a grayscale filter using CIImage and CIFilter, and a tint filter using UIGraphics context. Shows how to combine these dynamic filters with built-in filters using DynamicCompositeImageFilter and use them with the image downloader. ```swift import AlamofireImage // Create custom filter with closure let grayscaleFilter = DynamicImageFilter("grayscale") { image in guard let ciImage = CIImage(image: image), let filter = CIFilter(name: "CIColorControls") else { return image } filter.setValue(ciImage, forKey: kCIInputImageKey) filter.setValue(0.0, forKey: kCIInputSaturationKey) let context = CIContext() guard let outputImage = filter.outputImage, let cgImage = context.createCGImage(outputImage, from: outputImage.extent) else { return image } return UIImage(cgImage: cgImage, scale: image.scale, orientation: image.imageOrientation) } // Use custom filter let grayscaleImage = grayscaleFilter.filter(originalImage) // Create tint filter let tintFilter = DynamicImageFilter("tint-blue") { image in UIGraphicsBeginImageContextWithOptions(image.size, false, image.scale) defer { UIGraphicsEndImageContext() } image.draw(at: .zero) UIColor.blue.withAlphaComponent(0.3).setFill() UIRectFillUsingBlendMode(CGRect(origin: .zero, size: image.size), .sourceAtop) return UIGraphicsGetImageFromCurrentImageContext() ?? image } // Combine dynamic filters let combinedFilter = DynamicCompositeImageFilter( AspectScaledToFillSizeFilter(size: CGSize(width: 200, height: 200)), grayscaleFilter, RoundedCornersFilter(radius: 10) ) // Use with image downloader imageView.af.setImage(withURL: url, filter: combinedFilter) ``` -------------------------------- ### Install AlamofireImage with Carthage Source: https://github.com/alamofire/alamofireimage/blob/master/README.md Integrate AlamofireImage into your Xcode project using Carthage by specifying the dependency in your Cartfile. ```ogdl github "Alamofire/AlamofireImage" ~> 4.3 ``` -------------------------------- ### AlamofireImage Overview Source: https://github.com/alamofire/alamofireimage/blob/master/docs/index.html This section provides an overview of AlamofireImage's features, requirements, and migration guides. ```APIDOC ## AlamofireImage Overview ### Description AlamofireImage is an image component library for Alamofire that provides features such as image response serializers, UIImage extensions, image filters, caching, and downloading. ### Features * Image Response Serializers * UIImage Extensions for Inflation / Scaling / Rounding / CoreImage * Single and Multi-Pass Image Filters * Auto-Purging In-Memory Image Cache * Prioritized Queue Order Image Downloading * Authentication with URLCredential * UIImageView Async Remote Downloads with Placeholders * UIImageView Filters and Transitions * Comprehensive Test Coverage * Complete Documentation ### Requirements * iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+ / vision OS 1.0+ * Xcode 13+ * Swift 5.5+ ### Migration Guides * AlamofireImage 2.0 Migration Guide * AlamofireImage 3.0 Migration Guide ``` -------------------------------- ### Download Images with Swift Concurrency Source: https://context7.com/alamofire/alamofireimage/llms.txt Shows how to use the serializingImage method with async/await for modern, readable asynchronous image downloading. Includes examples for custom configurations and usage within an async context. ```swift import Alamofire import AlamofireImage // Using async/await for image downloads func downloadImage() async throws -> UIImage { let response = await AF.request("https://httpbin.org/image/jpeg") .serializingImage() .response switch response.result { case .success(let image): return image case .failure(let error): throw error } } // With custom parameters func downloadHDImage() async throws -> UIImage { let task = AF.request("https://example.com/hd-photo.jpg") .serializingImage( automaticallyCancelling: true, imageScale: 3.0, inflateResponseImage: true ) return try await task.value } ``` -------------------------------- ### Initialize ImageDownloader with Alamofire Session Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Classes/ImageDownloader.html Initializes an ImageDownloader instance using an existing Alamofire Session object. This is useful when integrating with an existing Alamofire setup, allowing control over download prioritization, active downloads, and image caching. ```Swift public init(session: Session, downloadPrioritization: DownloadPrioritization = .fifo, maximumActiveDownloads: Int = 4, imageCache: ImageRequestCache? = AutoPurgingImageCache()) ``` -------------------------------- ### Swift: Composite Image Filters with AlamofireImage Source: https://context7.com/alamofire/alamofireimage/llms.txt Demonstrates combining multiple image filters into a single operation for complex transformations. Includes examples of built-in composites like scaling and rounding corners, aspect filling and circling, and creating custom composite filters using DynamicCompositeImageFilter. Shows how to apply these filters when downloading images to a UIImageView. ```swift import AlamofireImage let image = UIImage(named: "photo")! let size = CGSize(width: 100, height: 100) // Built-in composite: Scale then round corners let scaledRoundedFilter = ScaledToSizeWithRoundedCornersFilter( size: size, radius: 10.0 ) let scaledRoundedImage = scaledRoundedFilter.filter(image) // Built-in composite: Aspect fill then round corners let fillRoundedFilter = AspectScaledToFillSizeWithRoundedCornersFilter( size: size, radius: 15.0, divideRadiusByImageScale: true ) // Built-in composite: Scale then circle let scaledCircleFilter = ScaledToSizeCircleFilter(size: size) let scaledCircleImage = scaledCircleFilter.filter(image) // Built-in composite: Aspect fill then circle (perfect for avatars) let avatarFilter = AspectScaledToFillSizeCircleFilter(size: size) let avatarImage = avatarFilter.filter(image) // Custom composite filter using DynamicCompositeImageFilter let customFilter = DynamicCompositeImageFilter( AspectScaledToFillSizeFilter(size: size), RoundedCornersFilter(radius: 20.0), BlurFilter(blurRadius: 5) ) let processedImage = customFilter.filter(image) // Use composite filter with UIImageView download imageView.af.setImage( withURL: url, placeholderImage: placeholder, filter: avatarFilter, imageTransition: .crossDissolve(0.2) ) ``` -------------------------------- ### Configure AlamofireImage ImageDownloader with Custom Settings Source: https://context7.com/alamofire/alamofireimage/llms.txt This Swift code demonstrates how to create and configure a custom ImageDownloader instance for AlamofireImage. It involves setting up a custom URLSessionConfiguration with specific cache policies and timeouts, defining a custom URLCache and an AutoPurgingImageCache, and then initializing the ImageDownloader with these custom components. The example also shows how to set this custom downloader as the shared downloader for UIImageView extensions or assign it to specific UIImageView instances. ```swift import Alamofire import AlamofireImage // Create custom URLSessionConfiguration let configuration = URLSessionConfiguration.default configuration.headers = .default configuration.httpShouldSetCookies = true configuration.timeoutIntervalForRequest = 30 configuration.requestCachePolicy = .returnCacheDataElseLoad // Create custom URLCache let memoryCapacity = 50 * 1024 * 1024 // 50 MB let diskCapacity = 200 * 1024 * 1024 // 200 MB configuration.urlCache = URLCache( memoryCapacity: memoryCapacity, diskCapacity: diskCapacity, diskPath: "com.app.imagecache" ) // Create image cache let imageCache = AutoPurgingImageCache( memoryCapacity: 150_000_000, preferredMemoryUsageAfterPurge: 100_000_000 ) // Create downloader with custom configuration let imageDownloader = ImageDownloader( configuration: configuration, downloadPrioritization: .fifo, maximumActiveDownloads: 6, imageCache: imageCache ) // Set as shared downloader for UIImageView UIImageView.af.sharedImageDownloader = imageDownloader // Or use custom Alamofire Session let session = Session(configuration: configuration, startRequestsImmediately: false) let customDownloader = ImageDownloader( session: session, downloadPrioritization: .lifo, maximumActiveDownloads: 4, imageCache: imageCache ) // Use per-instance downloader for specific image views let secureImageView = UIImageView() secureImageView.af.imageDownloader = customDownloader secureImageView.af.setImage(withURL: secureURL) ``` -------------------------------- ### Install AlamofireImage with Swift Package Manager Source: https://github.com/alamofire/alamofireimage/blob/master/README.md Add AlamofireImage as a dependency to your Swift package by providing its repository URL and version in Package.swift. ```swift dependencies: [ .package(url: "https://github.com/Alamofire/AlamofireImage.git", .upToNextMajor(from: "4.3.0")) ] ``` -------------------------------- ### Install AlamofireImage with CocoaPods Source: https://github.com/alamofire/alamofireimage/blob/master/README.md Integrate AlamofireImage into your Xcode project using CocoaPods by specifying the dependency in your Podfile. ```ruby pod 'AlamofireImage', '~> 4.3' ``` -------------------------------- ### GET /image(withIdentifier:) Source: https://github.com/alamofire/alamofireimage/blob/master/docs/docsets/AlamofireImage.docset/Contents/Resources/Documents/Classes/AutoPurgingImageCache.html Retrieves an image from the cache using a specific identifier. ```APIDOC ## GET image(withIdentifier:) ### Description Returns the image in the cache associated with the given identifier. ### Method GET ### Endpoint image(withIdentifier: String) ### Parameters #### Path Parameters - **identifier** (String) - Required - The unique identifier for the image. ### Response #### Success Response (200) - **Image** (UIImage) - The image if it is stored in the cache, nil otherwise. ``` -------------------------------- ### Initialization Methods Source: https://github.com/alamofire/alamofireimage/blob/master/docs/docsets/AlamofireImage.docset/Contents/Resources/Documents/Classes/ImageDownloader.html Methods to initialize the ImageDownloader with various configurations, sessions, and caching strategies. ```APIDOC ## Initialization ### Description Initializes the ImageDownloader instance with specific configurations, download prioritization, maximum active downloads, and image caching. ### Method INIT ### Parameters #### Path Parameters - **configuration** (URLSessionConfiguration) - Optional - The configuration for the underlying session. - **session** (Session) - Optional - The Alamofire Session instance. - **downloadPrioritization** (DownloadPrioritization) - Optional - Queue priority (default: .fifo). - **maximumActiveDownloads** (Int) - Optional - Max concurrent downloads (default: 4). - **imageCache** (ImageRequestCache) - Optional - Cache instance (default: AutoPurgingImageCache). ### Response Returns a new ImageDownloader instance. ``` -------------------------------- ### GET /imageCacheKey(for:withIdentifier:) Source: https://github.com/alamofire/alamofireimage/blob/master/docs/docsets/AlamofireImage.docset/Contents/Resources/Documents/Classes/AutoPurgingImageCache.html Generates a unique cache key for a given request and identifier. ```APIDOC ## GET imageCacheKey(for:withIdentifier:) ### Description Returns the unique image cache key for the specified request and additional identifier. ### Method GET ### Endpoint imageCacheKey(for: URLRequest, withIdentifier: String?) ### Parameters #### Path Parameters - **request** (URLRequest) - Required - The request. - **identifier** (String?) - Optional - The additional identifier. ### Response #### Success Response (200) - **Key** (String) - The unique image cache key. ``` -------------------------------- ### GET /image(for:withIdentifier:) Source: https://github.com/alamofire/alamofireimage/blob/master/docs/docsets/AlamofireImage.docset/Contents/Resources/Documents/Classes/AutoPurgingImageCache.html Retrieves an image from the cache using a URLRequest and an optional identifier. ```APIDOC ## GET image(for:withIdentifier:) ### Description Returns the image from the cache associated with an identifier created from the request and optional identifier. ### Method GET ### Endpoint image(for: URLRequest, withIdentifier: String?) ### Parameters #### Path Parameters - **request** (URLRequest) - Required - The request used to generate the image’s unique identifier. - **identifier** (String?) - Optional - The additional identifier to append to the image’s unique identifier. ### Response #### Success Response (200) - **Image** (UIImage) - The image if it is stored in the cache, nil otherwise. ``` -------------------------------- ### Initialize Git Repository Source: https://github.com/alamofire/alamofireimage/blob/master/README.md Initializes a new git repository in the current project directory. ```bash $ git init ``` -------------------------------- ### Initialize ImageDownloader Source: https://github.com/alamofire/alamofireimage/blob/master/README.md Configures an ImageDownloader instance with custom session configurations, download prioritization, and cache settings. ```swift let imageDownloader = ImageDownloader( configuration: ImageDownloader.defaultURLSessionConfiguration(), downloadPrioritization: .fifo, maximumActiveDownloads: 4, imageCache: AutoPurgingImageCache() ) ``` -------------------------------- ### Get Alamofire Image Downloader for UIButton Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Extensions/UIButton.html Retrieves the ImageDownloader instance associated with a UIButton. This property is deprecated. ```Swift public var af_imageDownloader: ImageDownloader? { get set } ``` -------------------------------- ### Image Cache: Getting an Image Source: https://github.com/alamofire/alamofireimage/blob/master/Documentation/AlamofireImage 3.0 Migration Guide.md Shows the updated method for retrieving cached images in AlamofireImage 3.0. ```APIDOC ## Image Cache: Getting an Image ### Description Illustrates the change in the method name for retrieving an image from the cache in AlamofireImage 3.0. ### Method N/A (Cache method) ### Endpoint N/A ### Request Example ```swift // AlamofireImage 2 let cachedAvatar = imageCache.imageWithIdentifier("avatar") // AlamofireImage 3 let cachedAvatar = imageCache.image(withIdentifier: "avatar") ``` ``` -------------------------------- ### Initialize ImageDownloader with Custom Configuration Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Classes/ImageDownloader.html Initializes an ImageDownloader instance with specific settings for URLSessionConfiguration, download prioritization, maximum active downloads, and an image cache. Allows for fine-grained control over the download process. ```Swift public init(configuration: URLSessionConfiguration = ImageDownloader.defaultURLSessionConfiguration(), downloadPrioritization: DownloadPrioritization = .fifo, maximumActiveDownloads: Int = 4, imageCache: ImageRequestCache? = AutoPurgingImageCache()) ``` -------------------------------- ### Initialization of ImageDownloader Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Classes/ImageDownloader.html Methods to initialize the ImageDownloader with custom configurations, sessions, and cache settings. ```APIDOC ## Initialization ### Description Initializes the ImageDownloader instance with various configurations, download prioritization, and caching strategies. ### Method Initializer ### Parameters #### Request Body - **configuration** (URLSessionConfiguration) - Optional - The configuration to use for the underlying session. - **session** (Session) - Optional - The Alamofire Session instance. - **downloadPrioritization** (DownloadPrioritization) - Optional - The queue prioritization (default: .fifo). - **maximumActiveDownloads** (Int) - Optional - Max concurrent downloads (default: 4). - **imageCache** (ImageRequestCache) - Optional - The cache instance to use. ### Response Returns a new ImageDownloader instance. ``` -------------------------------- ### Initialize and Configure BlurFilter Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Structs/BlurFilter.html Demonstrates how to initialize the BlurFilter struct and access its properties, including the filter name and CoreImage parameters. ```swift let blurFilter = BlurFilter(blurRadius: 15) let name = blurFilter.filterName let params = blurFilter.parameters ``` -------------------------------- ### Initialize ImageDownloader with Configuration Source: https://github.com/alamofire/alamofireimage/blob/master/docs/docsets/AlamofireImage.docset/Contents/Resources/Documents/Classes/ImageDownloader.html Initializes a new ImageDownloader instance using a URLSessionConfiguration. It allows customization of download prioritization, active download limits, and the image cache. ```swift public init(configuration: URLSessionConfiguration = ImageDownloader.defaultURLSessionConfiguration(), downloadPrioritization: DownloadPrioritization = .fifo, maximumActiveDownloads: Int = 4, imageCache: ImageRequestCache? = AutoPurgingImageCache()) ``` -------------------------------- ### Download Images with ImageDownloader Source: https://context7.com/alamofire/alamofireimage/llms.txt Demonstrates how to configure the ImageDownloader, perform single and batch downloads, apply image filters, track progress, and manage authentication. It also shows how to cancel requests using receipts. ```swift import AlamofireImage let downloader = ImageDownloader.default let customDownloader = ImageDownloader( configuration: ImageDownloader.defaultURLSessionConfiguration(), downloadPrioritization: .lifo, maximumActiveDownloads: 4, imageCache: AutoPurgingImageCache() ) let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/image/jpeg")!) downloader.download(urlRequest) { response in switch response.result { case .success(let image): print("Downloaded: \(image.size)") case .failure(let error): print("Error: \(error)") } } let filter = AspectScaledToFillSizeCircleFilter(size: CGSize(width: 100, height: 100)) downloader.download( urlRequest, filter: filter, progress: { progress in print("Progress: \(progress.fractionCompleted * 100)%") }, completion: { response in if case .success(let circularImage) = response.result { avatarImageView.image = circularImage } } ) let urls = [ URLRequest(url: URL(string: "https://example.com/image1.jpg")!), URLRequest(url: URL(string: "https://example.com/image2.jpg")!), URLRequest(url: URL(string: "https://example.com/image3.jpg")!) ] let receipts = downloader.download(urls) { response in print("Image downloaded: \(response.request?.url?.absoluteString ?? "")") } if let receipt = downloader.download(urlRequest, completion: nil) { downloader.cancelRequest(with: receipt) } downloader.addAuthentication(user: "username", password: "password") let credential = URLCredential(user: "user", password: "pass", persistence: .forSession) downloader.addAuthentication(usingCredential: credential) ``` -------------------------------- ### Get Shared Alamofire Image Downloader for UIButton Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Extensions/UIButton.html Retrieves the shared ImageDownloader instance used by AlamofireImage. This class property is deprecated. ```Swift public class var af_sharedImageDownloader: ImageDownloader { get set } ``` -------------------------------- ### Initiate Download Request Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Classes/ImageDownloader.html Initiates a download request for one or more URL requests. It allows for progress tracking and completion handling. ```APIDOC ## POST /download/requests ### Description Initiates one or more image download requests. This method handles the lifecycle of the download, including progress updates and completion callbacks. ### Method POST ### Endpoint /download/requests ### Parameters #### Request Body - **_urlRequests_** (Array) - Required - The URL requests to initiate. - **_progress_** (ProgressClosure?) - Optional - A closure to be executed periodically during the download lifecycle. - **_progressQueue_** (DispatchQueue) - Optional - The dispatch queue on which the progress closure should be called. Defaults to the main queue. - **_completion_** (CompletionClosure) - Required - The closure to be executed when each download request is complete. ### Response #### Success Response (200) - **receipts** (Array) - An array of request receipts for the initiated download requests. A receipt may not be returned if the image is found in the cache and the cache policy allows it. #### Response Example ```json { "receipts": [ { "request": { ... }, "taskIdentifier": 123, "progress": { ... } } ] } ``` ``` -------------------------------- ### Initialize ImageDownloader with Default Configuration Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Classes/ImageDownloader.html Provides static access to the default ImageDownloader instance. It's initialized with default values for configuration, prioritization, active downloads, and image caching. ```Swift public static let `default`: ImageDownloader ``` -------------------------------- ### GET responseImage Source: https://github.com/alamofire/alamofireimage/blob/master/Documentation/AlamofireImage 2.0 Migration Guide.md The responseImage method on the Request extension has been updated to support Alamofire 3.0 ResponseSerializer changes, using a generic Response type. ```APIDOC ## GET responseImage ### Description Serializes a network request response into an Image object using the updated Alamofire 3.0 response serializer pattern. ### Method GET ### Parameters #### Request Body - **imageScale** (CGFloat) - Optional - The scale factor to apply to the image. - **inflateResponseImage** (Bool) - Optional - Whether to inflate the image in the background thread. ### Request Example request.responseImage(imageScale: 2.0, inflateResponseImage: true) { response in ... } ### Response #### Success Response (200) - **response** (Response) - The generic response object containing the image or an error. ``` -------------------------------- ### Define AlamofireExtension for specific types Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Extensions.html Provides examples of how to constrain AlamofireExtension to specific types like UIButton, UIImage, or UIImageView to provide specialized functionality. ```Swift extension AlamofireExtension where ExtendedType: UIButton {} extension AlamofireExtension where ExtendedType: UIImage {} extension AlamofireExtension where ExtendedType: UIImageView {} ``` -------------------------------- ### Swift: Animated Image Transitions with AlamofireImage Source: https://context7.com/alamofire/alamofireimage/llms.txt Illustrates how to implement animated transitions when setting images on a UIImageView for smoother visual feedback. Covers built-in transitions like cross dissolve, curl down/up, and various flip effects. Also shows how to create custom transitions with completion handlers and how to ensure transitions run even for cached images. ```swift import AlamofireImage let imageView = UIImageView() let url = URL(string: "https://example.com/photo.jpg")! // Cross dissolve transition imageView.af.setImage( withURL: url, imageTransition: .crossDissolve(0.3) ) // Curl down transition imageView.af.setImage( withURL: url, imageTransition: .curlDown(0.5) ) // Curl up transition imageView.af.setImage( withURL: url, imageTransition: .curlUp(0.5) ) // Flip transitions imageView.af.setImage(withURL: url, imageTransition: .flipFromBottom(0.4)) imageView.af.setImage(withURL: url, imageTransition: .flipFromTop(0.4)) imageView.af.setImage(withURL: url, imageTransition: .flipFromLeft(0.4)) imageView.af.setImage(withURL: url, imageTransition: .flipFromRight(0.4)) // Custom transition with completion handler imageView.af.setImage( withURL: url, imageTransition: .custom( duration: 0.5, animationOptions: [.transitionCrossDissolve, .allowUserInteraction], animations: { imageView, image in imageView.transform = CGAffineTransform(scaleX: 0.8, y: 0.8) imageView.image = image }, completion: { finished in UIView.animate(withDuration: 0.2) { imageView.transform = .identity } } ) ) // Run transition even for cached images imageView.af.setImage( withURL: url, imageTransition: .crossDissolve(0.3), runImageTransitionIfCached: true ) ``` -------------------------------- ### run(_:with:) Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Extensions/AlamofireExtension.html Manually triggers an image transition animation on the UIImageView. ```APIDOC ## run(_:with:) ### Description Runs a specified image transition animation on the image view using the provided image. ### Method Swift Method ### Parameters - **imageTransition** (UIImageView.ImageTransition) - Required - The transition animation to perform. - **image** (Image) - Required - The image to display during the transition. ``` -------------------------------- ### Single Pass Image Filters Source: https://github.com/alamofire/alamofireimage/blob/master/README.md Single pass filters perform one image modification operation. Examples include scaling, rounding corners, and blurring. ```APIDOC ## Single Pass Image Filters ### Description Single pass image filters apply a single modification operation to an image. This includes filters for scaling, rounding corners, and applying blurs. ### Available Filters - `ScaledToSizeFilter`: Scales an image to a specified size. - `AspectScaledToFitSizeFilter`: Scales an image maintaining aspect ratio to fit within a specified size. - `AspectScaledToFillSizeFilter`: Scales an image maintaining aspect ratio to fill a specified size, clipping excess. - `RoundedCornersFilter`: Rounds the corners of an image. - `CircleFilter`: Rounds the corners of an image into a circle. - `BlurFilter`: Blurs an image with a specified radius. ### Usage Example ```swift let image = UIImage(named: "unicorn")! let imageFilter = RoundedCornersFilter(radius: 10.0) let roundedImage = imageFilter.filter(image) ``` ``` -------------------------------- ### Download and Filter Images Source: https://github.com/alamofire/alamofireimage/blob/master/README.md Shows how to initiate an image download request and optionally apply an ImageFilter to the resulting image. Ensure a strong reference to the downloader is maintained to prevent premature deallocation. ```swift let downloader = ImageDownloader() let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/image/jpeg")!) let filter = AspectScaledToFillSizeCircleFilter(size: CGSize(width: 100.0, height: 100.0)) downloader.download(urlRequest, filter: filter) { response in if case .success(let image) = response.result { print(image) } } ``` -------------------------------- ### Multi-Pass Image Filters Source: https://github.com/alamofire/alamofireimage/blob/master/README.md Multi-pass filters combine multiple image modification operations sequentially. Examples include scaling with rounded corners or creating circular images. ```APIDOC ## Multi-Pass Image Filters ### Description Multi-pass image filters perform a sequence of operations on an image. These filters are useful for combining multiple effects, such as scaling and rounding corners, or creating circular images. ### Available Filters - `ScaledToSizeWithRoundedCornersFilter`: Scales an image to a size and then rounds its corners. - `AspectScaledToFillSizeWithRoundedCornersFilter`: Scales an image to fit a size while maintaining aspect ratio, then rounds its corners. - `ScaledToSizeCircleFilter`: Scales an image to a size and then makes it circular. - `AspectScaledToFillSizeCircleFilter`: Scales an image to fit a size while maintaining aspect ratio, then makes it circular. ### Usage Example ```swift let image = UIImage(named: "avatar")! let size = CGSize(width: 100.0, height: 100.0) let imageFilter = AspectScaledToFillSizeCircleFilter(size: size) let avatarImage = imageFilter.filter(image) ``` ``` -------------------------------- ### Scale and Inflate UIImage with AlamofireImage Source: https://context7.com/alamofire/alamofireimage/llms.txt Demonstrates how to resize images using various scaling strategies including aspect-fit and aspect-fill. It also shows how to inflate images to improve drawing performance and check alpha properties. ```swift import AlamofireImage let image = UIImage(named: "photo")! let targetSize = CGSize(width: 200, height: 200) let scaledImage = image.af.imageScaled(to: targetSize) let fitImage = image.af.imageAspectScaled(toFit: targetSize) let fillImage = image.af.imageAspectScaled(toFill: targetSize) let lowResImage = image.af.imageScaled(to: targetSize, scale: 1.0) image.af.inflate() if !image.af.isInflated { image.af.inflate() } let hasAlpha = image.af.containsAlphaComponent let isOpaque = image.af.isOpaque ``` -------------------------------- ### Download an Image with ImageDownloader Source: https://github.com/alamofire/alamofireimage/blob/master/docs/index.html Shows how to perform a basic image download request. It highlights the importance of maintaining a strong reference to the downloader instance to ensure the completion closure executes. ```swift let downloader = ImageDownloader() let urlRequest = URLRequest(url: URL(string: "https://httpbin.org/image/jpeg")!) downloader.download(urlRequest) { response in print(response.request) print(response.response) debugPrint(response.result) if case .success(let image) = response.result { print(image) } } ``` -------------------------------- ### Initialize ScaledToSizeFilter Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Structs/ScaledToSizeFilter.html Demonstrates how to define and initialize the ScaledToSizeFilter structure with a specific target size. ```swift let size = CGSize(width: 100, height: 100) let filter = ScaledToSizeFilter(size: size) ``` -------------------------------- ### Scale UIImage Source: https://github.com/alamofire/alamofireimage/blob/master/docs/index.html Demonstrates various scaling operations including fixed size, aspect fit, and aspect fill. ```swift let image = UIImage(named: "unicorn")! let size = CGSize(width: 100.0, height: 100.0) let scaledImage = image.af.imageScaled(to: size) let aspectScaledToFitImage = image.af.imageAspectScaled(toFit: size) let aspectScaledToFillImage = image.af.imageAspectScaled(toFill: size) ``` -------------------------------- ### Initialize DynamicCompositeImageFilter Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Structs/DynamicCompositeImageFilter.html Demonstrates how to initialize the DynamicCompositeImageFilter using either an array of filters or a variadic list of filter objects. ```Swift let filters: [ImageFilter] = [BlurFilter(), CircleFilter()] let compositeFilter = DynamicCompositeImageFilter(filters) // Or using variadic initialization let variadicFilter = DynamicCompositeImageFilter(BlurFilter(), CircleFilter()) ``` -------------------------------- ### Combine Support Source: https://context7.com/alamofire/alamofireimage/llms.txt Shows how to integrate AlamofireImage with Combine for reactive image downloading. ```APIDOC ## Combine Support ### Description This section demonstrates how to use AlamofireImage with Apple's Combine framework to perform reactive image downloads using publishers. ### Method `AF.request(...).publishImage(...)` ### Endpoint N/A (This is a method extension on `DataRequest`) ### Parameters #### Request Body N/A #### Query Parameters N/A #### Path Parameters N/A ### Request Example ```swift import Alamofire import AlamofireImage import Combine var cancellables = Set() // Basic Combine publisher for image download AF.request("https://httpbin.org/image/png") .publishImage() .sink { // Handle completion switch $0 { case .finished: print("Download completed") case .failure(let error): print("Error: \(error)") } } receiveValue: { // Handle received image data if case .success(let image) = $0.result { // imageView.image = image } } .store(in: &cancellables) // With custom configuration and assignment AF.request("https://example.com/large-image.jpg") .publishImage( queue: .main, // Specify the queue for processing imageScale: UIScreen.main.scale, // Set image scale inflateResponseImage: true // Enable inflation ) .compactMap { $0.value } // Extract the UIImage if successful .receive(on: DispatchQueue.main) // Ensure UI updates on the main thread .assign(to: \.image, on: imageView) // Assign to UIImageView's image property .store(in: &cancellables) ``` ### Response #### Success Response (200) - **response** (ImageResponse) - A Combine `ImageResponse` containing the result of the image download and serialization. #### Response Example ```json { "result": { "success": "UIImage object" } } ``` ``` -------------------------------- ### Add, Fetch, and Remove Images from Cache (Swift) Source: https://github.com/alamofire/alamofireimage/blob/master/README.md Demonstrates basic operations on an ImageCache: adding an image with an identifier, fetching an image by its identifier, and removing an image from the cache. ```swift let imageCache = AutoPurgingImageCache() let avatarImage = UIImage(data: data)! // Add imageCache.add(avatarImage, withIdentifier: "avatar") // Fetch let cachedAvatar = imageCache.image(withIdentifier: "avatar") // Remove imageCache.removeImage(withIdentifier: "avatar") ``` -------------------------------- ### Download Images with Response Serializers Source: https://context7.com/alamofire/alamofireimage/llms.txt Demonstrates how to use the responseImage method to download and serialize image data. It covers basic requests, custom scaling, image inflation for performance, and configuring acceptable content types. ```swift import Alamofire import AlamofireImage // Basic image download with response serializer AF.request("https://httpbin.org/image/png").responseImage { response in switch response.result { case .success(let image): print("Image downloaded: \(image.size)") imageView.image = image case .failure(let error): print("Error: \(error)") } } // Custom image scale and inflation settings AF.request("https://example.com/photo.jpg").responseImage( imageScale: 2.0, inflateResponseImage: true ) { response in if case .success(let image) = response.result { // Image is pre-inflated for optimal drawing performance imageView.image = image } } // Add custom acceptable content types ImageResponseSerializer.addAcceptableImageContentTypes(["image/custom-type"]) ``` -------------------------------- ### Initialization Source: https://github.com/alamofire/alamofireimage/blob/master/docs/docsets/AlamofireImage.docset/Contents/Resources/Documents/Classes/AutoPurgingImageCache.html Initializes the AutoPurgingImageCache with specific memory capacity settings. ```APIDOC ## Initialization ### Description Initializes the `AutoPurgingImageCache` instance with the given memory capacity and preferred memory usage after purge limit. ### Method Constructor ### Parameters #### Request Body - **memoryCapacity** (UInt64) - Optional - The total memory capacity of the cache in bytes. Default: 100,000,000. - **preferredMemoryUsageAfterPurge** (UInt64) - Optional - The preferred memory usage after purge in bytes. Default: 60,000,000. ### Response - **instance** (AutoPurgingImageCache) - The new cache instance. ``` -------------------------------- ### UIImage and UIImageView Extensions: Loading Images with Options Source: https://github.com/alamofire/alamofireimage/blob/master/Documentation/AlamofireImage 3.0 Migration Guide.md Compares the method signatures for loading images with placeholders, filters, and transitions in AlamofireImage 3.0. ```APIDOC ## UIImage and UIImageView Extensions: Loading an Image with Placeholder, Filter and Transition ### Description Compares the syntax for loading images with additional options like placeholders, filters, and transitions between AlamofireImage 2.x and 3.0. ### Method N/A (Extension methods) ### Endpoint N/A ### Request Example ```swift // AlamofireImage 2 imageView.af_setImageWithURL( URL, placeholderImage: placeholderImage, filter: filter, imageTransition: .CrossDissolve(0.2) ) // AlamofireImage 3 imageView.af_setImage( withURL: url, placeholderImage: placeholderImage, filter: filter, imageTransition: .crossDissolve(0.2) ) ``` ``` -------------------------------- ### Swift Concurrency Support Source: https://context7.com/alamofire/alamofireimage/llms.txt Illustrates how to use AlamofireImage with Swift's async/await syntax for asynchronous image downloads. ```APIDOC ## Swift Concurrency Support ### Description This section explains how to leverage AlamofireImage with Swift's native `async/await` syntax using the `serializingImage` method for modern asynchronous programming. ### Method `AF.request(...).serializingImage().response` or `AF.request(...).serializingImage(...).value` ### Endpoint N/A (This is a method extension on `DataRequest`) ### Parameters #### Request Body N/A #### Query Parameters N/A #### Path Parameters N/A ### Request Example ```swift import Alamofire import AlamofireImage // Function to download an image using async/await func downloadImage() async throws -> UIImage { let response = await AF.request("https://httpbin.org/image/jpeg") .serializingImage() .response switch response.result { case .success(let image): return image case .failure(let error): throw error } } // Function with custom parameters func downloadHDImage() async throws -> UIImage { let task = AF.request("https://example.com/hd-photo.jpg") .serializingImage( automaticallyCancelling: true, imageScale: 3.0, inflateResponseImage: true ) return try await task.value } // Usage in an async context (e.g., SwiftUI View or Task) Task { do { let image = try await downloadImage() // Update UI on the main thread await MainActor.run { // imageView.image = image } } catch { print("Download failed: \(error)") } } ``` ### Response #### Success Response (200) - **UIImage** - The downloaded and serialized image. #### Response Example ```json { "image": "UIImage object" } ``` ``` -------------------------------- ### Download Images with Combine Source: https://context7.com/alamofire/alamofireimage/llms.txt Illustrates reactive image downloading using the publishImage method. This approach integrates with the Combine framework to handle image streams, custom configurations, and UI updates. ```swift import Alamofire import AlamofireImage import Combine var cancellables = Set() // Basic Combine publisher for image download AF.request("https://httpbin.org/image/png") .publishImage() .sink { completion in switch completion { case .finished: print("Download completed") case .failure(let error): print("Error: \(error)") } } receiveValue: { response in if case .success(let image) = response.result { imageView.image = image } } .store(in: &cancellables) // With custom configuration AF.request("https://example.com/large-image.jpg") .publishImage( queue: .main, imageScale: UIScreen.main.scale, inflateResponseImage: true ) .compactMap { $0.value } .receive(on: DispatchQueue.main) .assign(to: \.image, on: imageView) .store(in: &cancellables) ``` -------------------------------- ### Manage Memory Cache with AutoPurgingImageCache Source: https://context7.com/alamofire/alamofireimage/llms.txt Explains how to initialize an AutoPurgingImageCache with specific memory limits, add and retrieve images using identifiers, and perform cleanup operations. It also shows how to integrate the cache with an ImageDownloader. ```swift import AlamofireImage let imageCache = AutoPurgingImageCache( memoryCapacity: 100_000_000, preferredMemoryUsageAfterPurge: 60_000_000 ) let avatarImage = UIImage(named: "avatar")! imageCache.add(avatarImage, withIdentifier: "user-avatar") let urlRequest = URLRequest(url: URL(string: "https://example.com/photo.jpg")!) imageCache.add(avatarImage, for: urlRequest, withIdentifier: "circle") if let cachedAvatar = imageCache.image(withIdentifier: "user-avatar") { imageView.image = cachedAvatar } if let cachedImage = imageCache.image(for: urlRequest, withIdentifier: "circle") { imageView.image = cachedImage } imageCache.removeImage(withIdentifier: "user-avatar") imageCache.removeImage(for: urlRequest, withIdentifier: "circle") imageCache.removeImages(matching: urlRequest) imageCache.removeAllImages() print("Memory usage: \(imageCache.memoryUsage) bytes") print("Memory capacity: \(imageCache.memoryCapacity) bytes") let downloader = ImageDownloader( downloadPrioritization: .fifo, maximumActiveDownloads: 4, imageCache: imageCache ) ``` -------------------------------- ### Initialize AspectScaledToFillSizeFilter Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Structs/AspectScaledToFillSizeFilter.html Demonstrates how to initialize the filter with a specific CGSize. This filter will scale and crop images to the provided dimensions. ```swift let size = CGSize(width: 100, height: 100) let filter = AspectScaledToFillSizeFilter(size: size) ``` -------------------------------- ### Configure Authentication for Downloads Source: https://github.com/alamofire/alamofireimage/blob/master/README.md Adds HTTP Basic Authentication credentials to an ImageDownloader instance, which are then applied to all subsequent download requests. ```swift let downloader = ImageDownloader() downloader.addAuthentication(user: "username", password: "password") ``` -------------------------------- ### Define and Initialize DynamicImageFilter Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Structs/DynamicImageFilter.html Demonstrates how to declare the properties of the DynamicImageFilter and initialize it with a custom filter closure. ```swift public let identifier: String public let filter: (Image) -> Image public init(_ identifier: String, filter: @escaping (Image) -> Image) ``` -------------------------------- ### Migrating Image Cache Operations Source: https://github.com/alamofire/alamofireimage/blob/master/Documentation/AlamofireImage 3.0 Migration Guide.md Demonstrates the updated naming conventions for image cache operations including retrieving, adding, and removing images from the cache. ```swift // Getting an Image // AlamofireImage 2: imageCache.imageWithIdentifier("avatar") // AlamofireImage 3: imageCache.image(withIdentifier: "avatar") // Adding an Image // AlamofireImage 2: imageCache.addImage(avatarImage, withIdentifier: "avatar") // AlamofireImage 3: imageCache.add(avatarImage, withIdentifier: "avatar") // Removing an Image // AlamofireImage 2: imageCache.removeImageWithIdentifier("avatar") // AlamofireImage 3: imageCache.removeImage(withIdentifier: "avatar") ``` -------------------------------- ### Scale Images Source: https://github.com/alamofire/alamofireimage/blob/master/README.md Demonstrates scaling images to specific sizes, including maintaining aspect ratios for fit and fill operations. ```swift let image = UIImage(named: "unicorn")! let size = CGSize(width: 100.0, height: 100.0) // Scale image to size disregarding aspect ratio let scaledImage = image.af.imageScaled(to: size) // Scale image to fit within specified size while maintaining aspect ratio let aspectScaledToFitImage = image.af.imageAspectScaled(toFit: size) // Scale image to fill specified size while maintaining aspect ratio let aspectScaledToFillImage = image.af.imageAspectScaled(toFill: size) ``` -------------------------------- ### Define Image Transition Cases Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Extensions/UIImageView/ImageTransition.html Defines the available transition types for image loading. Includes built-in animations like flipFromTop and a custom case for providing specific animation parameters. ```swift case flipFromTop(TimeInterval) case custom(duration: TimeInterval, animationOptions: AnimationOptions, animations: (UIImageView, Image) -> Void, completion: ((Bool) -> Void)?) ``` -------------------------------- ### Run Image Transition Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Extensions/AlamofireExtension.html Executes a specific image transition animation on the UIImageView when setting a new image. ```swift public func run(_ imageTransition: UIImageView.ImageTransition, with image: Image) ``` -------------------------------- ### AspectScaledToFillSizeFilter Initialization and Filtering (Swift) Source: https://github.com/alamofire/alamofireimage/blob/master/docs/docsets/AlamofireImage.docset/Contents/Resources/Documents/Structs/AspectScaledToFillSizeFilter.html Demonstrates the initialization of AspectScaledToFillSizeFilter with a specific size and its associated filter closure for image manipulation. This filter scales an image to fill a given size, maintaining aspect ratio and clipping any overflow. ```swift public struct AspectScaledToFillSizeFilter : ImageFilter, Sizable { public let size: CGSize public init(size: CGSize) public var filter: (Image) -> Image { get } } ``` -------------------------------- ### ScaledToSizeFilter Initialization and Properties in Swift Source: https://github.com/alamofire/alamofireimage/blob/master/docs/docsets/AlamofireImage.docset/Contents/Resources/Documents/Structs/ScaledToSizeFilter.html Demonstrates the structure of ScaledToSizeFilter, including its initialization with a CGSize and its 'size' property. It also shows the 'filter' property which is a closure for image transformation. ```swift public struct ScaledToSizeFilter : ImageFilter, Sizable { public let size: CGSize public init(size: CGSize) public var filter: (Image) -> Image { get } } ``` -------------------------------- ### ImageResponseSerializer Initialization Source: https://github.com/alamofire/alamofireimage/blob/master/docs/docsets/AlamofireImage.docset/Contents/Resources/Documents/Classes/ImageResponseSerializer.html Initializes a new instance of the ImageResponseSerializer with specific configuration options for image processing. ```APIDOC ## init(imageScale:inflateResponseImage:emptyResponseCodes:emptyRequestMethods:) ### Description Initializes the serializer with parameters for scaling, image inflation, and handling empty responses. ### Method Initializer ### Parameters #### Request Body - **imageScale** (CGFloat) - Optional - The scale factor for the image (default: device screen scale). - **inflateResponseImage** (Bool) - Optional - Whether to inflate the image after decoding (default: true). - **emptyResponseCodes** (Set) - Optional - HTTP status codes considered empty. - **emptyRequestMethods** (Set) - Optional - HTTP methods considered empty. ### Request Example ImageResponseSerializer(imageScale: 2.0, inflateResponseImage: true) ``` -------------------------------- ### Image Transition Runner Source: https://github.com/alamofire/alamofireimage/blob/master/docs/docsets/AlamofireImage.docset/Contents/Resources/Documents/Extensions/UIImageView.html Method to manually run an image transition. ```APIDOC ### Image Transition Runner #### `run(_:with:)` - **Description**: Manually runs a specified `ImageTransition` with a given `Image`. - **Method**: `func` - **Endpoint**: N/A (Instance method) ### Parameters - **`imageTransition`** (`ImageTransition`) - The transition to run. - **`image`** (`Image`) - The image to apply the transition to. ### Request Example ```swift let transition = ImageTransition.fade(duration: 0.3) let image = UIImage(named: "myImage")! imageView.run(transition, with: image) ``` ``` -------------------------------- ### Image Scaling Utilities Source: https://github.com/alamofire/alamofireimage/blob/master/docs/docsets/AlamofireImage.docset/Contents/Resources/Documents/Extensions/AlamofireExtension.html Provides methods to scale images to specific sizes or fit within constraints while maintaining aspect ratios. ```swift public func imageScaled(to size: CGSize, scale: CGFloat? = nil) -> UIImage public func imageAspectScaled(toFit size: CGSize, scale: CGFloat? = nil) -> UIImage ``` -------------------------------- ### Load images into UIImageView with AlamofireImage Source: https://context7.com/alamofire/alamofireimage/llms.txt Demonstrates how to use the UIImageView extension to load images asynchronously. It supports placeholders, custom filters, transition animations, and completion handlers for tracking download progress and results. ```swift import AlamofireImage let imageView = UIImageView(frame: CGRect(x: 0, y: 0, width: 200, height: 200)) let url = URL(string: "https://httpbin.org/image/png")! let placeholderImage = UIImage(named: "placeholder")! // Simple image loading imageView.af.setImage(withURL: url) // With placeholder image imageView.af.setImage(withURL: url, placeholderImage: placeholderImage) // With image filter and cross-dissolve transition let filter = AspectScaledToFillSizeWithRoundedCornersFilter( size: imageView.frame.size, radius: 20.0 ) imageView.af.setImage( withURL: url, placeholderImage: placeholderImage, filter: filter, imageTransition: .crossDissolve(0.3) ) // Full configuration with progress and completion imageView.af.setImage( withURL: url, cacheKey: "unique-cache-key", placeholderImage: placeholderImage, filter: CircleFilter(), progress: { progress in print("Download progress: \(progress.fractionCompleted)") }, progressQueue: .main, imageTransition: .flipFromBottom(0.5), runImageTransitionIfCached: false, completion: { response in switch response.result { case .success(let image): print("Image loaded: \(image.size)") case .failure(let error): print("Failed: \(error)") } } ) // Cancel active download request imageView.af.cancelImageRequest() ``` -------------------------------- ### Image Transition Configuration Source: https://github.com/alamofire/alamofireimage/blob/master/docs/Extensions/UIImageView/ImageTransition.html Defines the available transition types and properties for image rendering in AlamofireImage. ```APIDOC ## Image Transition Types ### Description Defines how an image transitions into a UIImageView. ### Transition Cases - **flipFromTop(TimeInterval)** - Flips the image from the top. - **custom(duration, animationOptions, animations, completion)** - Allows for a fully custom animation block. ### Properties - **duration** (TimeInterval) - The duration of the image transition in seconds. - **animationOptions** (AnimationOptions) - The animation options used for the transition. - **animations** ((UIImageView, Image) -> Void) - The animation closure executed during the transition. - **completion** ((Bool) -> Void)? - The completion closure called after the animation finishes. ### Usage Example ```swift let transition = ImageTransition.flipFromTop(0.5) ``` ``` -------------------------------- ### ImageDownloader Configuration Source: https://github.com/alamofire/alamofireimage/blob/master/docs/docsets/AlamofireImage.docset/Contents/Resources/Documents/Classes/ImageDownloader.html Details regarding the properties and helper types used to configure the ImageDownloader instance. ```APIDOC ## ImageDownloader Configuration ### Description This section outlines the primary configuration properties and prioritization enums for the ImageDownloader class. ### DownloadPrioritization Defines the order prioritization of incoming download requests. - **fifo**: Incoming downloads are added to the back of the queue. - **lifo**: Incoming downloads are added to the front of the queue. ### Properties - **imageCache** (ImageRequestCache?) - The cache used to store downloaded images. - **credential** (URLCredential?) - The credential used for authenticating download requests. - **imageResponseSerializer** (ImageResponseSerializer) - Serializer used to convert image data to UIImage. - **session** (Session) - The underlying Alamofire Session instance. ### Declaration ```swift public enum DownloadPrioritization public let imageCache: ImageRequestCache? public let session: Session ``` ```