### YYWebImageManager Configuration and Usage Source: https://context7.com/ibireme/yywebimage/llms.txt This snippet demonstrates how to get the shared manager instance, configure various settings like timeout, headers, cache key filters, authentication, and global transformations. It also shows how to request an image with custom transformations and progress/completion blocks, and how to cancel operations and manage network activity count. ```APIDOC ## YYWebImageManager Configuration and Usage ### Description This section covers the initialization and configuration of `YYWebImageManager`, including setting global options and performing image requests. ### Method N/A (Configuration and direct image requests) ### Endpoint N/A (In-memory manager) ### Parameters #### Manager Configuration Properties - **timeout** (double) - Default: 15.0 - The timeout interval in seconds for image download requests. - **headers** (NSDictionary) - Custom HTTP headers to be sent with all requests. - **headersFilter** (^(NSURL *url, NSDictionary *header) -> NSDictionary *) - A block to dynamically filter or modify HTTP headers based on the request URL. - **cacheKeyFilter** (^(NSURL *url) -> NSString *) - A block to customize the cache key generation for downloaded images. - **username** (NSString *) - Username for basic authentication. - **password** (NSString *) - Password for basic authentication. - **sharedTransformBlock** (^(UIImage *image, NSURL *url) -> UIImage *) - A global block applied as a transformation to all downloaded images before caching or completion. #### Image Request Parameters - **requestImageWithURL** (NSURL *) - The URL of the image to download. - **options** (YYWebImageOptions) - Options to control the image loading behavior (e.g., `YYWebImageOptionSetImageWithFadeAnimation`). - **progress** (^(NSInteger receivedSize, NSInteger expectedSize)) - A block called periodically to report download progress. - **transform** (^(UIImage *image, NSURL *url) -> UIImage *) - A block to apply a specific transformation to the downloaded image for this request. - **completion** (^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error)) - A block called when the image request is completed or fails. ### Network Activity Management - **incrementNetworkActivityCount**() - Increments the global network activity counter. - **decrementNetworkActivityCount**() - Decrements the global network activity counter. - **currentNetworkActivityCount**() -> NSInteger - Returns the current value of the network activity counter. ### Request Example (Image Download) ```objc // Get shared manager instance YYWebImageManager *manager = [YYWebImageManager sharedManager]; // Configure timeout manager.timeout = 30.0; // Set custom HTTP headers manager.headers = @{ @"Accept": @"image/webp,image/*;q=0.8", @"User-Agent": @"MyApp/1.0" }; // Request image with progress, transform, and completion blocks YYWebImageOperation *operation = [manager requestImageWithURL:[NSURL URLWithString:@"https://example.com/photo.jpg"] options:YYWebImageOptionSetImageWithFadeAnimation progress:^(NSInteger receivedSize, NSInteger expectedSize) { NSLog(@"Download: %ld/%ld bytes", (long)receivedSize, (long)expectedSize); } transform:^UIImage *(UIImage *image, NSURL *url) { return [image yy_imageByResizeToSize:CGSizeMake(200, 200) contentMode:UIViewContentModeScaleAspectFill]; } completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (stage == YYWebImageStageFinished) { // Use the processed image dispatch_async(dispatch_get_main_queue(), ^{ self.imageView.image = image; }); } }]; // Cancel specific operation [operation cancel]; // Network activity indicator management [YYWebImageManager incrementNetworkActivityCount]; // ... perform network operations ... [YYWebImageManager decrementNetworkActivityCount]; NSInteger activeCount = [YYWebImageManager currentNetworkActivityCount]; ``` ### Response #### Success Response (Completion Block) - **image** (UIImage *) - The downloaded and processed image. - **url** (NSURL *) - The original URL of the image. - **from** (YYWebImageFromType) - The source of the image (e.g., memory cache, disk cache, network). - **stage** (YYWebImageStage) - The stage of the image loading process (e.g., finished, cancelled). #### Error Response (Completion Block) - **error** (NSError *) - An error object if the image failed to download or process. ### Response Example (Completion Block) ```json { "image": "UIImage object", "url": "https://example.com/photo.jpg", "from": "YYWebImageFromNetwork", "stage": "YYWebImageStageFinished", "error": null } ``` ``` -------------------------------- ### Implementing Custom Image Loading with YYWebImageOperation Source: https://context7.com/ibireme/yywebimage/llms.txt Demonstrates how to initialize and configure a YYWebImageOperation with custom headers, image transformations, and completion handlers. It also shows how to manage the operation lifecycle, including authentication and queue execution. ```objective-c #import NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://example.com/image.jpg"]]; [request setValue:@"MyApp/1.0" forHTTPHeaderField:@"User-Agent"]; [request setValue:@"image/webp,image/*;q=0.8" forHTTPHeaderField:@"Accept"]; request.timeoutInterval = 30.0; YYImageCache *cache = [YYImageCache sharedCache]; NSString *cacheKey = @"custom_cache_key"; YYWebImageOperation *operation = [[YYWebImageOperation alloc] initWithRequest:request options:YYWebImageOptionProgressiveBlur | YYWebImageOptionSetImageWithFadeAnimation cache:cache cacheKey:cacheKey progress:^(NSInteger receivedSize, NSInteger expectedSize) { CGFloat progress = expectedSize > 0 ? (CGFloat)receivedSize / expectedSize : 0; NSLog(@"Download progress: %.1f%%", progress * 100); } transform:^UIImage *(UIImage *image, NSURL *url) { @autoreleasepool { image = [image yy_imageByResizeToSize:CGSizeMake(300, 300) contentMode:UIViewContentModeScaleAspectFill]; return [image yy_imageByRoundCornerRadius:10]; } } completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (error) { NSLog(@"Error: %@", error.localizedDescription); return; } switch (stage) { case YYWebImageStageProgress: NSLog(@"Progressive image update"); break; case YYWebImageStageFinished: NSLog(@"Download complete from: %@", from == YYWebImageFromMemoryCacheFast ? @"Memory (fast)" : from == YYWebImageFromMemoryCache ? @"Memory" : from == YYWebImageFromDiskCache ? @"Disk" : @"Remote"); dispatch_async(dispatch_get_main_queue(), ^{ self.imageView.image = image; }); break; case YYWebImageStageCancelled: NSLog(@"Operation cancelled"); break; } }]; operation.shouldUseCredentialStorage = YES; operation.credential = [NSURLCredential credentialWithUser:@"user" password:@"password" persistence:NSURLCredentialPersistenceForSession]; [operation start]; NSOperationQueue *queue = [[NSOperationQueue alloc] init]; queue.maxConcurrentOperationCount = 4; [queue addOperation:operation]; ``` -------------------------------- ### Configure and Use YYWebImageManager Source: https://context7.com/ibireme/yywebimage/llms.txt Demonstrates how to configure the shared YYWebImageManager instance with custom headers, cache keys, and authentication. It also shows how to perform an image request with custom transformations and progress tracking. ```objective-c #import YYWebImageManager *manager = [YYWebImageManager sharedManager]; manager.timeout = 30.0; manager.headers = @{@"Accept": @"image/webp,image/*;q=0.8", @"User-Agent": @"MyApp/1.0"}; manager.headersFilter = ^NSDictionary *(NSURL *url, NSDictionary *header) { NSMutableDictionary *newHeaders = [header mutableCopy]; if ([url.host containsString:@"secure.example.com"]) { newHeaders[@"Authorization"] = @"Bearer token123"; } return newHeaders; }; manager.cacheKeyFilter = ^NSString *(NSURL *url) { NSURLComponents *components = [NSURLComponents componentsWithURL:url resolvingAgainstBaseURL:NO]; components.query = nil; return components.URL.absoluteString; }; manager.username = @"user"; manager.password = @"password"; manager.sharedTransformBlock = ^UIImage *(UIImage *image, NSURL *url) { return [image yy_imageByRoundCornerRadius:5]; }; YYWebImageOperation *operation = [manager requestImageWithURL:[NSURL URLWithString:@"https://example.com/photo.jpg"] options:YYWebImageOptionSetImageWithFadeAnimation progress:^(NSInteger receivedSize, NSInteger expectedSize) { NSLog(@"Download: %ld/%ld bytes", (long)receivedSize, (long)expectedSize); } transform:^UIImage *(UIImage *image, NSURL *url) { return [image yy_imageByResizeToSize:CGSizeMake(200, 200) contentMode:UIViewContentModeScaleAspectFill]; } completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (stage == YYWebImageStageFinished) { dispatch_async(dispatch_get_main_queue(), ^{ self.imageView.image = image; }); } }]; [operation cancel]; [YYWebImageManager incrementNetworkActivityCount]; [YYWebImageManager decrementNetworkActivityCount]; ``` -------------------------------- ### Configure Image Loading with YYWebImageOptions Source: https://context7.com/ibireme/yywebimage/llms.txt Demonstrates how to use various YYWebImageOption flags to control network activity, progressive loading, caching behavior, and display animations. These options can be combined using bitwise OR operators to tailor the loading experience. ```objc #import UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)]; // Show network activity indicator [imageView yy_setImageWithURL:url options:YYWebImageOptionShowNetworkActivity]; // Progressive download modes [imageView yy_setImageWithURL:url options:YYWebImageOptionProgressive]; // Standard progressive [imageView yy_setImageWithURL:url options:YYWebImageOptionProgressiveBlur]; // Progressive with blur // Cache control options [imageView yy_setImageWithURL:url options:YYWebImageOptionRefreshImageCache]; // Always fetch from remote [imageView yy_setImageWithURL:url options:YYWebImageOptionIgnoreDiskCache]; // Skip disk cache [imageView yy_setImageWithURL:url options:YYWebImageOptionUseNSURLCache]; // Use NSURLCache instead // Display options [imageView yy_setImageWithURL:url options:YYWebImageOptionSetImageWithFadeAnimation]; // Fade animation [imageView yy_setImageWithURL:url options:YYWebImageOptionIgnorePlaceHolder]; // Don't show placeholder [imageView yy_setImageWithURL:url options:YYWebImageOptionAvoidSetImage]; // Don't auto-set image // Image processing options [imageView yy_setImageWithURL:url options:YYWebImageOptionIgnoreImageDecoding]; // Skip decoding [imageView yy_setImageWithURL:url options:YYWebImageOptionIgnoreAnimatedImage]; // Treat animated as static // Network options [imageView yy_setImageWithURL:url options:YYWebImageOptionAllowInvalidSSLCertificates]; // Allow untrusted SSL [imageView yy_setImageWithURL:url options:YYWebImageOptionAllowBackgroundTask]; // Continue in background [imageView yy_setImageWithURL:url options:YYWebImageOptionHandleCookies]; // Handle cookies // Error handling [imageView yy_setImageWithURL:url options:YYWebImageOptionIgnoreFailedURL]; // Blacklist failed URLs // Combined options for optimal experience YYWebImageOptions combinedOptions = YYWebImageOptionShowNetworkActivity | YYWebImageOptionProgressiveBlur | YYWebImageOptionSetImageWithFadeAnimation | YYWebImageOptionAllowBackgroundTask; [imageView yy_setImageWithURL:url options:combinedOptions]; ``` -------------------------------- ### Implement Progressive Image Loading with YYWebImage Source: https://context7.com/ibireme/yywebimage/llms.txt Shows how to enable progressive image rendering, including blur effects and download progress tracking for a better user experience. ```objc #import UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)]; [imageView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/large_photo.jpg"] options:YYWebImageOptionProgressive]; [imageView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/large_photo.jpg"] options:YYWebImageOptionProgressiveBlur | YYWebImageOptionSetImageWithFadeAnimation]; [imageView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/large_photo.jpg"] placeholder:nil options:YYWebImageOptionProgressiveBlur | YYWebImageOptionSetImageWithFadeAnimation progress:^(NSInteger receivedSize, NSInteger expectedSize) { CGFloat progress = expectedSize > 0 ? (CGFloat)receivedSize / expectedSize : 0; NSLog(@"Download progress: %.1f%%", progress * 100); dispatch_async(dispatch_get_main_queue(), ^{ progressView.progress = progress; }); } transform:nil completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (stage == YYWebImageStageFinished && !error) { NSLog(@"Progressive image fully loaded"); } }]; ``` -------------------------------- ### Apply Real-time Image Transformations with YYWebImage Source: https://context7.com/ibireme/yywebimage/llms.txt Demonstrates how to apply various image transformations such as resizing, rounding corners, blurring, and adding borders during image download using YYWebImage. It shows how to use the `transform` block for custom image manipulation before displaying it in a `UIImageView`. ```objc #import UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; // Download, resize, and add round corners [imageView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/avatar.jpg"] placeholder:[UIImage imageNamed:@"avatar_placeholder"] options:YYWebImageOptionSetImageWithFadeAnimation progress:^(NSInteger receivedSize, NSInteger expectedSize) { CGFloat progress = (CGFloat)receivedSize / expectedSize; NSLog(@"Progress: %.0f%%", progress * 100); } transform:^UIImage *(UIImage *image, NSURL *url) { @autoreleasepool { // Resize to exact dimensions image = [image yy_imageByResizeToSize:CGSizeMake(100, 100) contentMode:UIViewContentModeScaleAspectFill]; // Add round corners image = [image yy_imageByRoundCornerRadius:50]; return image; } } completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (from == YYWebImageFromDiskCache) { NSLog(@"Loaded processed image from disk cache"); } }]; // Complex transformation with blur, tint, and border [imageView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/photo.jpg"] placeholder:nil options:YYWebImageOptionSetImageWithFadeAnimation progress:nil transform:^UIImage *(UIImage *image, NSURL *url) { @autoreleasepool { // Resize with aspect fill image = [image yy_imageByResizeToSize:CGSizeMake(200, 200) contentMode:UIViewContentModeScaleAspectFill]; // Apply blur with tint image = [image yy_imageByBlurRadius:20 tintColor:[[UIColor blackColor] colorWithAlphaComponent:0.3] tintMode:kCGBlendModeNormal saturation:1.2 maskImage:nil]; // Add round corners with border image = [image yy_imageByRoundCornerRadius:10 borderWidth:2.0 borderColor:[UIColor whiteColor]]; return image; } } completion:nil]; ``` -------------------------------- ### Configure and Manage YYMemoryCache Source: https://context7.com/ibireme/yywebimage/llms.txt Demonstrates how to set up memory limits, handle memory warnings, and perform manual object operations in YYMemoryCache. It includes configuration for auto-trimming and thread-safe object release. ```objective-c #import YYImageCache *imageCache = [YYWebImageManager sharedManager].cache; YYMemoryCache *memoryCache = imageCache.memoryCache; memoryCache.countLimit = 100; memoryCache.costLimit = 50 * 1024 * 1024; memoryCache.ageLimit = 60 * 60; memoryCache.autoTrimInterval = 5.0; memoryCache.shouldRemoveAllObjectsOnMemoryWarning = YES; memoryCache.shouldRemoveAllObjectsWhenEnteringBackground = YES; memoryCache.didReceiveMemoryWarningBlock = ^(YYMemoryCache *cache) { NSLog(@"Memory warning! Cache count: %lu", (unsigned long)cache.totalCount); [cache removeAllObjects]; }; memoryCache.releaseOnMainThread = YES; memoryCache.releaseAsynchronously = YES; [memoryCache setObject:image forKey:@"key"]; UIImage *obj = [memoryCache objectForKey:@"key"]; ``` -------------------------------- ### Initialize Cacheless YYWebImageManager Source: https://context7.com/ibireme/yywebimage/llms.txt Shows how to create a manager without a cache for temporary image requests, ensuring that images are not persisted to disk or memory. ```objc YYWebImageManager *noCacheManager = [[YYWebImageManager alloc] initWithCache:nil queue:nil]; [noCacheManager requestImageWithURL:[NSURL URLWithString:@"https://example.com/temp.jpg"] options:0 progress:nil transform:nil completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { // Image not cached }]; ``` -------------------------------- ### Create UIImage from Color, Drawing, and GIF Data (Objective-C) Source: https://context7.com/ibireme/yywebimage/llms.txt Demonstrates how to create UIImage objects from solid colors, custom drawing blocks, and small GIF data using YYWebImage extensions. These methods are useful for generating placeholder images or loading animated GIFs efficiently. ```Objective-C #import // Create solid color image UIImage *redImage = [UIImage yy_imageWithColor:[UIColor redColor]]; UIImage *sizedColor = [UIImage yy_imageWithColor:[UIColor blueColor] size:CGSizeMake(100, 100)]; // Create with custom drawing UIImage *customImage = [UIImage yy_imageWithSize:CGSizeMake(100, 100) drawBlock:^(CGContextRef context) { [[UIColor redColor] setFill]; CGContextFillEllipseInRect(context, CGRectMake(0, 0, 100, 100)); }]; // Create from small GIF data NSData *gifData = [NSData dataWithContentsOfFile:@"animation.gif"]; UIImage *animatedGIF = [UIImage yy_imageWithSmallGIFData:gifData scale:2.0]; ``` -------------------------------- ### Load Images into UIImageView with YYWebImage Source: https://context7.com/ibireme/yywebimage/llms.txt Demonstrates how to load images into a UIImageView using URL or local file paths. Includes options for placeholders, fade animations, and completion handling. ```objc #import UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)]; imageView.yy_imageURL = [NSURL URLWithString:@"https://example.com/photo.jpg"]; imageView.yy_imageURL = [NSURL fileURLWithPath:@"/tmp/cached_image.png"]; UIImage *placeholder = [UIImage imageNamed:@"placeholder"]; [imageView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/photo.jpg"] placeholder:placeholder]; [imageView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/photo.jpg"] placeholder:placeholder options:YYWebImageOptionSetImageWithFadeAnimation completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (error) { NSLog(@"Image load failed: %@", error.localizedDescription); return; } if (stage == YYWebImageStageFinished) { NSLog(@"Image loaded from: %@", from == YYWebImageFromMemoryCache ? @"Memory" : from == YYWebImageFromDiskCache ? @"Disk" : @"Remote"); } }]; [imageView yy_cancelCurrentImageRequest]; ``` -------------------------------- ### YYWebImageOperation Usage Source: https://context7.com/ibireme/yywebimage/llms.txt Demonstrates how to create, configure, and manage a YYWebImageOperation for custom image loading workflows. ```APIDOC ## YYWebImageOperation ### Description Low-level NSOperation subclass for custom image loading workflows with full control over the download process. ### Method Not Applicable (This is a class for manual operation management) ### Endpoint Not Applicable ### Parameters This section describes the parameters used when initializing `YYWebImageOperation`. #### Initialization Parameters - **request** (NSMutableURLRequest) - Required - The URL request for the image. - **options** (YYWebImageOptions) - Optional - Options to control image loading behavior (e.g., progressive blur, fade animation). - **cache** (YYImageCache) - Optional - The image cache instance to use. - **cacheKey** (NSString) - Optional - The key to use for caching the image. - **progress** (YYWebImageProgressBlock) - Optional - A block to receive download progress updates. - **transform** (YYWebImageTransformBlock) - Optional - A block to transform the downloaded image (e.g., resize, round corners). - **completion** (YYWebImageCompletionBlock) - Required - A block to handle the completion of the operation (success, failure, or cancellation). ### Request Example ```objc // Create URL request with custom headers NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:[NSURL URLWithString:@"https://example.com/image.jpg"]]; [request setValue:@"MyApp/1.0" forHTTPHeaderField:@"User-Agent"]; [request setValue:@"image/webp,image/*;q=0.8" forHTTPHeaderField:@"Accept"]; request.timeoutInterval = 30.0; // Get cache YYImageCache *cache = [YYImageCache sharedCache]; NSString *cacheKey = @"custom_cache_key"; // Create operation YYWebImageOperation *operation = [[YYWebImageOperation alloc] initWithRequest:request options:YYWebImageOptionProgressiveBlur | YYWebImageOptionSetImageWithFadeAnimation cache:cache cacheKey:cacheKey progress:^(NSInteger receivedSize, NSInteger expectedSize) { CGFloat progress = expectedSize > 0 ? (CGFloat)receivedSize / expectedSize : 0; NSLog(@"Download progress: %.1f%%", progress * 100); } transform:^UIImage *(UIImage *image, NSURL *url) { @autoreleasepool { image = [image yy_imageByResizeToSize:CGSizeMake(300, 300) contentMode:UIViewContentModeScaleAspectFill]; return [image yy_imageByRoundCornerRadius:10]; } } completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (error) { NSLog(@"Error: %@", error.localizedDescription); return; } switch (stage) { case YYWebImageStageProgress: NSLog(@"Progressive image update"); break; case YYWebImageStageFinished: NSLog(@"Download complete from: %@", from == YYWebImageFromMemoryCacheFast ? @"Memory (fast)" : from == YYWebImageFromMemoryCache ? @"Memory" : from == YYWebImageFromDiskCache ? @"Disk" : @"Remote"); dispatch_async(dispatch_get_main_queue(), ^{ self.imageView.image = image; }); break; case YYWebImageStageCancelled: NSLog(@"Operation cancelled"); break; } }]; // Configure authentication operation.shouldUseCredentialStorage = YES; operation.credential = [NSURLCredential credentialWithUser:@"user" password:@"password" persistence:NSURLCredentialPersistenceForSession]; // Start operation manually [operation start]; // Or add to operation queue for managed execution NSOperationQueue *queue = [[NSOperationQueue alloc] init]; queue.maxConcurrentOperationCount = 4; [queue addOperation:operation]; // Access operation properties NSURLRequest *req = operation.request; NSURLResponse *response = operation.response; YYWebImageOptions options = operation.options; NSString *key = operation.cacheKey; // Cancel operation [operation cancel]; ``` ### Response #### Success Response (200) - **image** (UIImage) - The loaded and potentially transformed image. - **url** (NSURL) - The URL of the image. - **from** (YYWebImageFromType) - The source of the image (cache, memory, disk, remote). - **stage** (YYWebImageStage) - The stage of the operation (progress, finished, cancelled). #### Error Response (Non-200) - **error** (NSError) - An error object describing the failure. ### Response Example ```json { "image": "UIImage object", "url": "https://example.com/image.jpg", "from": "Remote", "stage": "Finished" } ``` ``` -------------------------------- ### Manage Image Caching with YYImageCache Source: https://context7.com/ibireme/yywebimage/llms.txt Explains how to interact with the YYImageCache to store, retrieve, and remove images from memory and disk. It covers both synchronous and asynchronous operations, as well as custom cache initialization. ```objc #import // Get shared cache or manager's cache YYImageCache *cache = [YYImageCache sharedCache]; // Create custom cache with specific path YYImageCache *customCache = [[YYImageCache alloc] initWithPath:@"/path/to/cache"]; customCache.name = @"MyAppImageCache"; customCache.allowAnimatedImage = YES; // Enable animated image decoding customCache.decodeForDisplay = YES; // Decode to bitmap for performance // Store image in cache UIImage *image = [UIImage imageNamed:@"photo"]; [cache setImage:image forKey:@"unique_key"]; // Store with specific cache type NSData *imageData = UIImagePNGRepresentation(image); [cache setImage:image imageData:imageData forKey:@"photo_key" withType:YYImageCacheTypeAll]; // Retrieve image asynchronously [cache getImageForKey:@"unique_key" withType:YYImageCacheTypeAll withBlock:^(UIImage *image, YYImageCacheType type) { dispatch_async(dispatch_get_main_queue(), ^{ if (image) { NSLog(@"Found in %@", type == YYImageCacheTypeMemory ? @"memory" : @"disk"); self.imageView.image = image; } }); }]; // Check if image exists BOOL exists = [cache containsImageForKey:@"unique_key"]; // Remove image [cache removeImageForKey:@"unique_key"]; ``` -------------------------------- ### Load Images into UIButton with YYWebImage Source: https://context7.com/ibireme/yywebimage/llms.txt Demonstrates how to load foreground and background images for specific UIButton states, apply image transformations, and manage request lifecycles. It supports placeholders, fade animations, and completion callbacks. ```objc #import UIButton *button = [UIButton buttonWithType:UIButtonTypeCustom]; button.frame = CGRectMake(0, 0, 150, 50); [button yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/icon_normal.png"] forState:UIControlStateNormal placeholder:[UIImage imageNamed:@"icon_placeholder"]]; [button yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/icon_highlighted.png"] forState:UIControlStateHighlighted options:YYWebImageOptionSetImageWithFadeAnimation]; [button yy_setBackgroundImageWithURL:[NSURL URLWithString:@"https://example.com/button_bg.png"] forState:UIControlStateNormal placeholder:nil options:YYWebImageOptionSetImageWithFadeAnimation completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (!error) { NSLog(@"Button background loaded"); } }]; [button yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/large_icon.png"] forState:UIControlStateNormal placeholder:nil options:YYWebImageOptionSetImageWithFadeAnimation progress:nil transform:^UIImage *(UIImage *image, NSURL *url) { return [image yy_imageByResizeToSize:CGSizeMake(44, 44) contentMode:UIViewContentModeScaleAspectFit]; } completion:nil]; NSURL *currentURL = [button yy_imageURLForState:UIControlStateNormal]; NSLog(@"Current normal state URL: %@", currentURL); [button yy_cancelImageRequestForState:UIControlStateNormal]; [button yy_cancelBackgroundImageRequestForState:UIControlStateNormal]; ``` -------------------------------- ### Display Animated Images with YYWebImage Source: https://context7.com/ibireme/yywebimage/llms.txt Shows how to load and display animated image formats like GIF, WebP, and APNG using `YYAnimatedImageView`. It covers loading directly via URL, handling placeholders, options, and ignoring animation to treat animated files as static images. Also includes creating an animated image from local GIF data. ```objc #import // Use YYAnimatedImageView for animated images YYAnimatedImageView *animatedImageView = [[YYAnimatedImageView alloc] initWithFrame:CGRectMake(0, 0, 200, 200)]; // Load animated WebP animatedImageView.yy_imageURL = [NSURL URLWithString:@"https://example.com/animation.webp"]; // Load animated GIF with options [animatedImageView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/animation.gif"] placeholder:[UIImage imageNamed:@"loading"] options:YYWebImageOptionSetImageWithFadeAnimation completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (!error && stage == YYWebImageStageFinished) { NSLog(@"Animated image loaded successfully"); } }]; // Load APNG (Animated PNG) [animatedImageView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/animation.apng"] options:YYWebImageOptionShowNetworkActivity]; // Ignore animation and treat as static image UIImageView *staticView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 100, 100)]; [staticView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/animation.gif"] options:YYWebImageOptionIgnoreAnimatedImage]; // Create animated image from local GIF data NSData *gifData = [NSData dataWithContentsOfFile:@"/path/to/animation.gif"]; UIImage *animatedImage = [UIImage yy_imageWithSmallGIFData:gifData scale:[UIScreen mainScreen].scale]; animatedImageView.image = animatedImage; ``` -------------------------------- ### Load Animated Image Source: https://github.com/ibireme/yywebimage/blob/master/README.md Shows how to display animated images like WebP by using the YYAnimatedImageView class. ```objective-c UIImageView *imageView = [YYAnimatedImageView new]; imageView.yy_imageURL = [NSURL URLWithString:@"http://github.com/ani.webp"]; ``` -------------------------------- ### Configure Custom YYWebImageManager for Specialized Caching Source: https://context7.com/ibireme/yywebimage/llms.txt This snippet demonstrates how to initialize a custom YYWebImageManager with a dedicated cache and operation queue. It includes setting memory/disk limits, defining a global transformation block for circular avatars, and using the manager with a UIImageView. ```objc #import NSString *avatarCachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"AvatarCache"]; YYImageCache *avatarCache = [[YYImageCache alloc] initWithPath:avatarCachePath]; avatarCache.name = @"AvatarCache"; avatarCache.memoryCache.countLimit = 50; avatarCache.memoryCache.costLimit = 10 * 1024 * 1024; avatarCache.diskCache.countLimit = 500; avatarCache.diskCache.costLimit = 50 * 1024 * 1024; avatarCache.diskCache.ageLimit = 7 * 24 * 60 * 60; NSOperationQueue *avatarQueue = [[NSOperationQueue alloc] init]; avatarQueue.name = @"com.myapp.avatar-download"; avatarQueue.maxConcurrentOperationCount = 3; YYWebImageManager *avatarManager = [[YYWebImageManager alloc] initWithCache:avatarCache queue:avatarQueue]; avatarManager.timeout = 10.0; avatarManager.headers = @{@"Accept": @"image/png,image/jpeg"}; avatarManager.sharedTransformBlock = ^UIImage *(UIImage *image, NSURL *url) { image = [image yy_imageByResizeToSize:CGSizeMake(100, 100) contentMode:UIViewContentModeScaleAspectFill]; return [image yy_imageByRoundCornerRadius:50]; }; UIImageView *avatarView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; [avatarView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/avatar/user123.jpg"] placeholder:[UIImage imageNamed:@"default_avatar"] options:YYWebImageOptionSetImageWithFadeAnimation manager:avatarManager progress:nil transform:nil completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (!error) { NSLog(@"Avatar loaded"); } }]; ``` -------------------------------- ### Progressive Image Loading Source: https://context7.com/ibireme/yywebimage/llms.txt Display images progressively as they download, with optional blur effects for a polished user experience. ```APIDOC ## Progressive Image Loading ### Description Display images progressively as they download, with optional blur effects for a polished user experience. ### Method Category methods for UIImageView ### Endpoint N/A (Category Methods) ### Parameters #### Path Parameters None #### Query Parameters None #### Request Body None ### Request Example ```objc #import UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 300, 300)]; // Basic progressive loading - shows image as it downloads [imageView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/large_photo.jpg"] options:YYWebImageOptionProgressive]; // Progressive with blur effect and fade animation (recommended for best UX) [imageView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/large_photo.jpg"] options:YYWebImageOptionProgressiveBlur | YYWebImageOptionSetImageWithFadeAnimation]; // Progressive loading with download progress tracking [imageView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/large_photo.jpg"] placeholder:nil options:YYWebImageOptionProgressiveBlur | YYWebImageOptionSetImageWithFadeAnimation progress:^(NSInteger receivedSize, NSInteger expectedSize) { CGFloat progress = expectedSize > 0 ? (CGFloat)receivedSize / expectedSize : 0; NSLog(@"Download progress: %.1f%%", progress * 100); // Update progress UI on main thread dispatch_async(dispatch_get_main_queue(), ^{ progressView.progress = progress; }); } transform:nil completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (stage == YYWebImageStageFinished && !error) { NSLog(@"Progressive image fully loaded"); } }]; ``` ### Response #### Success Response (200) N/A (Category Methods) #### Response Example N/A ``` -------------------------------- ### Resize and Crop UIImage (Objective-C) Source: https://context7.com/ibireme/yywebimage/llms.txt Provides methods for resizing and cropping UIImage objects using YYWebImage extensions. Supports simple resizing, aspect fit/fill content modes, cropping to a specific rectangle, and adding padding with a specified color. ```Objective-C #import UIImage *originalImage = [UIImage imageNamed:@"photo"]; // Simple resize (stretches image) UIImage *resized = [originalImage yy_imageByResizeToSize:CGSizeMake(200, 200)]; // Resize with content mode UIImage *aspectFill = [originalImage yy_imageByResizeToSize:CGSizeMake(200, 200) contentMode:UIViewContentModeScaleAspectFill]; UIImage *aspectFit = [originalImage yy_imageByResizeToSize:CGSizeMake(200, 200) contentMode:UIViewContentModeScaleAspectFit]; // Crop to rect UIImage *cropped = [originalImage yy_imageByCropToRect:CGRectMake(50, 50, 100, 100)]; // Add inset/padding UIImage *padded = [originalImage yy_imageByInsetEdge:UIEdgeInsetsMake(10, 10, 10, 10) withColor:[UIColor whiteColor]]; ``` -------------------------------- ### Apply Visual Effects to UIImage (Objective-C) Source: https://context7.com/ibireme/yywebimage/llms.txt Shows how to apply various visual effects to UIImage objects using YYWebImage extensions, including tinting, converting to grayscale, and applying different types of blurs (soft, light, extra-light, dark) with customizable parameters. ```Objective-C #import UIImage *originalImage = [UIImage imageNamed:@"photo"]; // Tint color UIImage *tinted = [originalImage yy_imageByTintColor:[UIColor colorWithRed:0 green:0.5 blue:1 alpha:0.3]]; // Grayscale UIImage *grayscale = [originalImage yy_imageByGrayscale]; // Blur effects UIImage *softBlur = [originalImage yy_imageByBlurSoft]; UIImage *lightBlur = [originalImage yy_imageByBlurLight]; // iOS Control Panel style UIImage *extraLight = [originalImage yy_imageByBlurExtraLight]; // Navigation Bar White style UIImage *darkBlur = [originalImage yy_imageByBlurDark]; // Notification Center style // Blur with tint UIImage *tintedBlur = [originalImage yy_imageByBlurWithTint:[[UIColor blueColor] colorWithAlphaComponent:0.2]]; // Custom blur with full control UIImage *customBlur = [originalImage yy_imageByBlurRadius:15.0 tintColor:[[UIColor whiteColor] colorWithAlphaComponent:0.4] tintMode:kCGBlendModeNormal saturation:1.8 maskImage:nil]; // Check alpha channel BOOL hasAlpha = [originalImage yy_hasAlphaChannel]; ``` -------------------------------- ### Custom YYWebImageManager Configuration Source: https://context7.com/ibireme/yywebimage/llms.txt This snippet demonstrates how to create a custom YYWebImageManager with a dedicated cache and operation queue, including setting cache limits, queue concurrency, timeout, headers, and a shared image transform block. ```APIDOC ## Custom YYWebImageManager Configuration ### Description This section details the process of creating and configuring a custom `YYWebImageManager` instance. This allows for isolated caching, specific operation queues, and tailored image transformations for different parts of your application. ### Method Objective-C ### Endpoint N/A (Configuration within application code) ### Parameters N/A (Configuration via code) ### Request Example ```objc #import // Create custom cache for specific content type NSString *avatarCachePath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES).firstObject stringByAppendingPathComponent:@"AvatarCache"]; YYImageCache *avatarCache = [[YYImageCache alloc] initWithPath:avatarCachePath]; avatarCache.name = @"AvatarCache"; avatarCache.memoryCache.countLimit = 50; avatarCache.memoryCache.costLimit = 10 * 1024 * 1024; // 10MB avatarCache.diskCache.countLimit = 500; avatarCache.diskCache.costLimit = 50 * 1024 * 1024; // 50MB avatarCache.diskCache.ageLimit = 7 * 24 * 60 * 60; // 7 days // Create operation queue with concurrency limit NSOperationQueue *avatarQueue = [[NSOperationQueue alloc] init]; avatarQueue.name = @"com.myapp.avatar-download"; avatarQueue.maxConcurrentOperationCount = 3; // Create custom manager YYWebImageManager *avatarManager = [[YYWebImageManager alloc] initWithCache:avatarCache queue:avatarQueue]; avatarManager.timeout = 10.0; avatarManager.headers = @{@"Accept": @"image/png,image/jpeg"}; // Global transform for all avatars avatarManager.sharedTransformBlock = ^UIImage *(UIImage *image, NSURL *url) { image = [image yy_imageByResizeToSize:CGSizeMake(100, 100) contentMode:UIViewContentModeScaleAspectFill]; return [image yy_imageByRoundCornerRadius:50]; // Circular avatars }; // Use custom manager with UIImageView UIImageView *avatarView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 50, 50)]; [avatarView yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/avatar/user123.jpg"] placeholder:[UIImage imageNamed:@"default_avatar"] options:YYWebImageOptionSetImageWithFadeAnimation manager:avatarManager progress:nil transform:nil // Uses manager's sharedTransformBlock completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (!error) { NSLog(@"Avatar loaded"); } }]; // Cancel all operations in custom manager [avatarQueue cancelAllOperations]; // Create manager without cache (for temporary images) YYWebImageManager *noCacheManager = [[YYWebImageManager alloc] initWithCache:nil queue:nil]; [noCacheManager requestImageWithURL:[NSURL URLWithString:@"https://example.com/temp.jpg"] options:0 progress:nil transform:nil completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { // Image not cached }]; ``` ### Response N/A (Configuration within application code) ### Response Example N/A ``` -------------------------------- ### Load Image Progressively Source: https://github.com/ibireme/yywebimage/blob/master/README.md Configures progressive image loading with optional blur and fade animation effects. ```objective-c [imageView yy_setImageWithURL:url options:YYWebImageOptionProgressive]; [imageView yy_setImageWithURL:url options:YYWebImageOptionProgressiveBlur | YYWebImageOptionSetImageWithFadeAnimation]; ``` -------------------------------- ### Load Images into CALayer with YYWebImage Source: https://context7.com/ibireme/yywebimage/llms.txt Shows how to load remote images directly into a CALayer's contents. This includes support for placeholders, progressive loading, custom image transformations like grayscale, and request cancellation. ```objc #import CALayer *layer = [CALayer layer]; layer.frame = CGRectMake(0, 0, 200, 200); [self.view.layer addSublayer:layer]; layer.yy_imageURL = [NSURL URLWithString:@"https://example.com/texture.png"]; [layer yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/texture.png"] placeholder:[UIImage imageNamed:@"default_texture"]]; [layer yy_setImageWithURL:[NSURL URLWithString:@"https://example.com/texture.png"] placeholder:[UIImage imageNamed:@"default_texture"] options:YYWebImageOptionSetImageWithFadeAnimation | YYWebImageOptionProgressiveBlur progress:^(NSInteger receivedSize, NSInteger expectedSize) { NSLog(@"Layer image progress: %.0f%%", (CGFloat)receivedSize / expectedSize * 100); } transform:^UIImage *(UIImage *image, NSURL *url) { return [image yy_imageByGrayscale]; } completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (!error && stage == YYWebImageStageFinished) { NSLog(@"Layer texture loaded"); } }]; [layer yy_cancelCurrentImageRequest]; ``` -------------------------------- ### Rotate and Flip UIImage (Objective-C) Source: https://context7.com/ibireme/yywebimage/llms.txt Demonstrates UIImage rotation and flipping operations using YYWebImage extensions. Supports rotating by arbitrary angles, 90-degree increments, 180 degrees, and vertical/horizontal flips. ```Objective-C #import UIImage *originalImage = [UIImage imageNamed:@"photo"]; UIImage *rotated = [originalImage yy_imageByRotate:M_PI_4 fitSize:YES]; // 45 degrees UIImage *left90 = [originalImage yy_imageByRotateLeft90]; UIImage *right90 = [originalImage yy_imageByRotateRight90]; UIImage *rotate180 = [originalImage yy_imageByRotate180]; UIImage *flipV = [originalImage yy_imageByFlipVertical]; UIImage *flipH = [originalImage yy_imageByFlipHorizontal]; ``` -------------------------------- ### Load Image from URL Source: https://github.com/ibireme/yywebimage/blob/master/README.md Demonstrates how to load images from remote or local URLs into a UIImageView using the yy_imageURL property. ```objective-c imageView.yy_imageURL = [NSURL URLWithString:@"http://github.com/logo.png"]; imageView.yy_imageURL = [NSURL fileURLWithPath:@"/tmp/logo.png"]; ``` -------------------------------- ### Load and Process Image Source: https://github.com/ibireme/yywebimage/blob/master/README.md Performs advanced image loading including progress tracking, custom image transformation (resize/round corner), and completion handling. ```objective-c [imageView yy_setImageWithURL:url placeholder:nil options:YYWebImageOptionSetImageWithFadeAnimation progress:^(NSInteger receivedSize, NSInteger expectedSize) { progress = (float)receivedSize / expectedSize; } transform:^UIImage *(UIImage *image, NSURL *url) { image = [image yy_imageByResizeToSize:CGSizeMake(100, 100) contentMode:UIViewContentModeCenter]; return [image yy_imageByRoundCornerRadius:10]; } completion:^(UIImage *image, NSURL *url, YYWebImageFromType from, YYWebImageStage stage, NSError *error) { if (from == YYWebImageFromDiskCache) { NSLog(@"load from disk cache"); } }]; ``` -------------------------------- ### Configure and Manage YYDiskCache Source: https://context7.com/ibireme/yywebimage/llms.txt Covers persistent storage management using YYDiskCache, including asynchronous operations, disk space monitoring, and progress-tracked cache clearing. ```objective-c #import YYImageCache *imageCache = [YYWebImageManager sharedManager].cache; YYDiskCache *diskCache = imageCache.diskCache; diskCache.countLimit = 1000; diskCache.costLimit = 200 * 1024 * 1024; diskCache.freeDiskSpaceLimit = 100 * 1024 * 1024; [diskCache setObject:image forKey:@"key" withBlock:^{ NSLog(@"Image saved to disk"); }]; [diskCache removeAllObjectsWithProgressBlock:^(int removedCount, int totalCount) { CGFloat progress = (CGFloat)removedCount / totalCount; NSLog(@"Clearing cache: %.0f%%", progress * 100); } endBlock:^(BOOL error) { NSLog(@"Cache cleared, error: %@", error ? @"YES" : @"NO"); }]; ```