### Implementing a Custom NetworkImageLoader with Delay Source: https://context7.com/gonzalezreal/networkimage/llms.txt Shows how to create a custom NetworkImageLoader by conforming to the protocol. This example adds a delay to the image loading process, which is useful for testing loading states. The custom loader is applied using the .networkImageLoader modifier. ```swift import CoreGraphics import Foundation import NetworkImage // Custom loader that adds a delay (useful for testing loading states) final class DelayNetworkImageLoader: NetworkImageLoader { private let delay: TimeInterval init(delay: TimeInterval) { self.delay = delay } func image(from url: URL) async throws -> CGImage { try await Task.sleep(nanoseconds: UInt64(delay * 1_000_000_000)) return try await DefaultNetworkImageLoader.shared.image(from: url) } } // Usage in SwiftUI view struct DelayedImageView: View { var body: some View { NetworkImage(url: URL(string: "https://picsum.photos/id/1025/300/200")) { state in switch state { case .empty: ProgressView() case .success(let image, _): image.resizable().scaledToFit() case .failure: Image(systemName: "exclamationmark.triangle") } } .frame(width: 200, height: 200) .networkImageLoader(DelayNetworkImageLoader(delay: 2)) } } ``` -------------------------------- ### Using DefaultNetworkImageLoader Source: https://context7.com/gonzalezreal/networkimage/llms.txt Demonstrates how to access the shared DefaultNetworkImageLoader and how to create a custom loader with specific cache and session configurations. It also shows how to load an image programmatically using the loader. ```swift import NetworkImage import Foundation // Access the shared default loader let sharedLoader = DefaultNetworkImageLoader.shared // Create a custom loader with specific cache and session configuration let customCache = DefaultNetworkImageCache(countLimit: 50) let customSession = URLSession.imageLoading( memoryCapacity: 20 * 1024 * 1024, // 20 MB memory cache diskCapacity: 200 * 1024 * 1024, // 200 MB disk cache timeoutInterval: 30 // 30 second timeout ) let customLoader = DefaultNetworkImageLoader(cache: customCache, session: customSession) // Load an image programmatically Task { do { let cgImage = try await sharedLoader.image(from: URL(string: "https://picsum.photos/300/200")!) print("Image loaded: \(cgImage.width)x\(cgImage.height)") } catch { print("Failed to load image: \(error)") } } ``` -------------------------------- ### NetworkImage with Loading State Control Source: https://github.com/gonzalezreal/networkimage/blob/main/README.md Use the `init(url:scale:transaction:content)` initializer and a `switch` statement on `NetworkImageState` for fine-grained control over the loading process, including empty, success, and failure states. ```swift NetworkImage(url: URL(string: "https://picsum.photos/id/237/300/200")) { state in switch state { case .empty: ProgressView() case .success(let image, let idealSize): image .resizable() .scaledToFill() case .failure: Image(systemName: "photo.fill") .imageScale(.large) .blendMode(.overlay) } } .frame(width: 150, height: 150) .background(Color.secondary.opacity(0.25)) .clipped() ``` -------------------------------- ### Basic NetworkImage Usage Source: https://github.com/gonzalezreal/networkimage/blob/main/README.md Use this initializer to display an image from a URL. The image is downloaded asynchronously and cached. ```swift NetworkImage(url: URL(string: "https://picsum.photos/id/237/300/200")) .frame(width: 300, height: 200) ``` -------------------------------- ### Basic NetworkImage Initialization Source: https://context7.com/gonzalezreal/networkimage/llms.txt Use the basic initializer for simple remote image display. It handles downloading and caching automatically. A custom scale can be provided for high-resolution displays. ```swift import SwiftUI import NetworkImage struct BasicImageView: View { var body: some View { // Simple network image with default placeholder NetworkImage(url: URL(string: "https://picsum.photos/id/237/300/200")) .frame(width: 300, height: 200) // With custom scale for high-resolution displays NetworkImage(url: URL(string: "https://picsum.photos/id/1025/600/400"), scale: 2.0) .frame(width: 300, height: 200) .clipShape(RoundedRectangle(cornerRadius: 8)) } } ``` -------------------------------- ### Configuring DefaultNetworkImageCache Source: https://context7.com/gonzalezreal/networkimage/llms.txt Illustrates how to use the DefaultNetworkImageCache for in-memory image storage. It shows how to access the shared cache, create a custom cache with a specific count limit, and check for cached images. Manual caching is also mentioned but typically handled by the loader. ```swift import NetworkImage import CoreGraphics import Foundation // Use the shared cache with default 100 image limit let sharedCache = DefaultNetworkImageCache.shared // Create a custom cache with specific count limit let customCache = DefaultNetworkImageCache(countLimit: 200) // Check for cached image let url = URL(string: "https://picsum.photos/id/237/300/200")! if let cachedImage = customCache.image(for: url) { print("Found cached image: \(cachedImage.width)x\(cachedImage.height)") } // Manually cache an image (typically handled automatically by the loader) // customCache.setImage(someCGImage, for: url) ``` -------------------------------- ### Create Optimized URLSession for Images Source: https://context7.com/gonzalezreal/networkimage/llms.txt Create a `URLSession` optimized for image downloading with configurable memory and disk cache sizes, and a specific timeout interval. This session is automatically configured with a suitable request cache policy and Accept header. ```swift import Foundation import NetworkImage // Create an image-optimized URLSession let imageSession = URLSession.imageLoading( memoryCapacity: 10 * 1024 * 1024, // 10 MB in-memory cache diskCapacity: 100 * 1024 * 1024, // 100 MB on-disk cache timeoutInterval: 15 // 15 second timeout ) // The session is configured with: // - requestCachePolicy: .returnCacheDataElseLoad // - Accept header: "image/*" // - Custom URLCache with specified capacities // Use with custom DefaultNetworkImageLoader let customLoader = DefaultNetworkImageLoader( cache: DefaultNetworkImageCache(countLimit: 100), session: imageSession ) ``` -------------------------------- ### Handling NetworkImage Loading States Source: https://context7.com/gonzalezreal/networkimage/llms.txt Demonstrates how to handle the different states of an image loading operation using the NetworkImageState enum. This includes displaying a placeholder or loading indicator for .empty and .failure states, and showing the loaded image for .success. ```swift import SwiftUI import NetworkImage // NetworkImageState has three cases: // - .empty: No image is loaded yet (loading in progress) // - .success(image: Image, idealSize: CGSize): Image loaded successfully // - .failure: Image failed to load struct StateHandlingView: View { var body: some View { NetworkImage(url: URL(string: "https://example.com/image.jpg")) { state in // Access the image directly via computed property if let image = state.image { image.resizable().scaledToFit() } else { // Handles both .empty and .failure states Color.gray.overlay { if case .failure = state { Text("Failed to load") } else { ProgressView() } } } } .frame(width: 200, height: 200) } } ``` -------------------------------- ### NetworkImage with Full State Control Source: https://context7.com/gonzalezreal/networkimage/llms.txt Gain complete control over the image loading process using an initializer that provides `NetworkImageState`. This allows handling empty (loading), success, and failure states with custom views. ```swift import SwiftUI import NetworkImage struct FullStateControlView: View { var body: some View { NetworkImage( url: URL(string: "https://picsum.photos/id/237/300/200"), transaction: .init(animation: .default) ) { state in switch state { case .empty: ProgressView() case .success(let image, let idealSize): image .resizable() .scaledToFill() case .failure: Image(systemName: "photo.fill") .imageScale(.large) .blendMode(.overlay) } } .frame(width: 150, height: 150) .background(Color.secondary.opacity(0.25)) .clipped() } } ``` -------------------------------- ### Add NetworkImage to Swift Package Manager Project Source: https://github.com/gonzalezreal/networkimage/blob/main/README.md Add the NetworkImage package to your project's dependencies in `Package.swift` and import it into your source files. ```swift .package(url: "https://github.com/gonzalezreal/NetworkImage", from: "6.0.0") ``` ```swift .target(name: "", dependencies: [ .product(name: "NetworkImage", package: "NetworkImage") ]), ``` -------------------------------- ### NetworkImage with Custom Placeholder Source: https://github.com/gonzalezreal/networkimage/blob/main/README.md Provide a custom placeholder view using the `placeholder` parameter, which is displayed until the image successfully loads. ```swift NetworkImage(url: URL(string: "https://picsum.photos/id/237/300/200")) { image in image .resizable() .scaledToFill() } placeholder: { ZStack { Color.secondary.opacity(0.25) Image(systemName: "photo.fill") .imageScale(.large) .blendMode(.overlay) } } .frame(width: 150, height: 150) .clipped() ``` -------------------------------- ### Display Images in a LazyVStack Source: https://context7.com/gonzalezreal/networkimage/llms.txt Efficiently display a list of remote images using `NetworkImage` within a `LazyVStack`. This approach ensures smooth scrolling and automatic memory management for a large number of images. ```swift import SwiftUI import NetworkImage struct ImageListView: View { struct ImageItem: Identifiable { let id = UUID() let imageURL: URL? init(imageId: Int) { self.imageURL = URL(string: "https://picsum.photos/id/ romParams: $0)/400/300") } } let items = (1...100).map { ImageItem(imageId: $0) } var body: some View { ScrollView { LazyVStack(spacing: 16) { ForEach(items) { item in NetworkImage( url: item.imageURL, transaction: .init(animation: .default) ) { image in image .resizable() .scaledToFill() } .aspectRatio(1.333, contentMode: .fill) .clipShape(RoundedRectangle(cornerRadius: 8)) .overlay { RoundedRectangle(cornerRadius: 8) .strokeBorder(Color.primary.opacity(0.25), lineWidth: 0.5) } } } .padding() } } } ``` -------------------------------- ### NetworkImage with Content Manipulation Source: https://github.com/gonzalezreal/networkimage/blob/main/README.md Use the `content` parameter to apply modifiers to the loaded image, such as resizing and scaling. ```swift NetworkImage(url: URL(string: "https://picsum.photos/id/237/300/200")) { image in image .resizable() .scaledToFill() .blur(radius: 4) } .frame(width: 150, height: 150) .clipped() ``` -------------------------------- ### NetworkImage with Image Transformation Source: https://context7.com/gonzalezreal/networkimage/llms.txt Manipulate and style the loaded image using the content closure. This provides access to the SwiftUI Image view for applying standard modifiers like resizing and effects. ```swift import SwiftUI import NetworkImage struct StyledImageView: View { var body: some View { // Apply resizing, scaling, and visual effects NetworkImage(url: URL(string: "https://picsum.photos/id/237/300/200")) { image in image .resizable() .scaledToFill() .blur(radius: 4) } .frame(width: 150, height: 150) .clipped() // Grayscale effect example NetworkImage(url: URL(string: "https://picsum.photos/id/1025/300/200")) { image in image .resizable() .scaledToFill() .grayscale(1) } .frame(width: 200, height: 200) .clipShape(RoundedRectangle(cornerRadius: 8)) } } ``` -------------------------------- ### Set Custom NetworkImage Loader Source: https://context7.com/gonzalezreal/networkimage/llms.txt Use the `networkImageLoader` modifier to set a custom image loader for all NetworkImage views within a SwiftUI view hierarchy. This is useful for injecting specific loading logic or test loaders. ```swift import SwiftUI import NetworkImage struct AppContentView: View { var body: some View { // All NetworkImage views in this hierarchy use the custom loader VStack { NetworkImage(url: URL(string: "https://picsum.photos/id/1/300/200")) .frame(width: 150, height: 100) NetworkImage(url: URL(string: "https://picsum.photos/id/2/300/200")) .frame(width: 150, height: 100) } .networkImageLoader(DefaultNetworkImageLoader.shared) } } // Inject a test loader for SwiftUI previews struct PreviewImageView: View { var body: some View { NetworkImage(url: URL(string: "https://example.com/test.jpg")) { state in switch state { case .empty: ProgressView() case .success(let image, _): image case .failure: Color.red } } .networkImageLoader(DelayNetworkImageLoader(delay: 1)) } } ``` === COMPLETE CONTENT === This response contains all available snippets from this library. No additional content exists. Do not make further requests.