### CocoaPods Installation Options for HXPhotoPicker Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Guides for integrating HXPhotoPicker using CocoaPods. Various subspecs are available to include specific functionalities like GIF support, network image loading with SDWebImage or Kingfisher, or isolating components like Picker, Editor, or Camera. ```ruby pod 'HXPhotoPicker' pod 'HXPhotoPicker/SwiftyGif' pod 'HXPhotoPicker/SDWebImage' pod 'HXPhotoPicker/Kingfisher' pod 'HXPhotoPicker/Picker' pod 'HXPhotoPicker/Editor' pod 'HXPhotoPicker/Camera' pod 'HXPhotoPicker/Camera/Lite' ``` -------------------------------- ### Manage Animation with HxPhotoPicker (Swift) Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Provides methods to start and stop animations for an image view. These are likely wrappers around underlying animation mechanisms. ```swift public func _startAnimating() { startAnimating() } public func _stopAnimating() { stopAnimating() } ``` -------------------------------- ### Implement PhotoPickerControllerDelegate for Media Selection Source: https://context7.com/silencelove/hxphotopicker/llms.txt This snippet demonstrates how to conform to the PhotoPickerControllerDelegate protocol to handle user selection, cancellation, and lifecycle events. It includes examples of processing selected assets using modern Swift async/await syntax and legacy callback methods, as well as how to apply custom validation logic to restrict selection based on asset properties. ```swift import HXPhotoPicker class ViewController: UIViewController, PhotoPickerControllerDelegate { func pickerController(_ pickerController: PhotoPickerController, didFinishSelection result: PickerResult) { Task { let images: [UIImage] = try await result.objects() let urls: [URL] = try await result.objects() let compressedImages: [UIImage] = try await result.objects(.init(imageCompressionQuality: 0.5)) } result.getImage { image, photoAsset, index in print("Processing \(index): \(photoAsset.mediaType)") } completionHandler: { images in print("Got \(images.count) images") } } func pickerController(didCancel pickerController: PhotoPickerController) { pickerController.dismiss(animated: true) } func pickerController(_ pickerController: PhotoPickerController, didDismissComplete localCameraAssetArray: [PhotoAsset]) { self.savedCameraAssets = localCameraAssetArray } func pickerController(_ pickerController: PhotoPickerController, shouldSelectedAsset photoAsset: PhotoAsset, atIndex: Int) -> Bool { if photoAsset.mediaType == .video && photoAsset.videoDuration > 30 { return false } return true } } ``` -------------------------------- ### GET /PhotoAsset/Media Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/RELEASE_NOTE.md Retrieves various media types from a PhotoAsset, including thumbnails, full previews, and video assets. ```APIDOC ## GET /PhotoAsset/Media ### Description Asynchronously requests different media representations of a PhotoAsset. ### Method GET ### Endpoint photoAsset.request[MediaType]() ### Parameters None ### Request Example let thumImage = try await photoAsset.requesThumbnailImage() let avAsset = try await photoAsset.requestAVAsset() ### Response #### Success Response (200) - **Media** (Object) - Returns requested media type (UIImage, AVAsset, PlayerItem, or LivePhoto). #### Response Example { "status": "success", "data": "MediaObject" } ``` -------------------------------- ### Swift Package Manager Installation for HXPhotoPicker Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Instructions for adding HXPhotoPicker to your project using Swift Package Manager. Requires Xcode 13.0+ for full resource and localization support. This method ensures easy dependency management and updates. ```swift dependencies: [ .package(url: "https://github.com/SilenceLove/HXPhotoPicker.git", .upToNextMajor(from: "5.0.5")) ] ``` -------------------------------- ### Get Other Asset Types from Photo Asset (Swift) Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Provides methods to asynchronously request various representations of a photo asset, including thumbnail images, preview images, AVAsset, AVPlayerItem, and PHLivePhoto objects. ```swift let thumImage = try await photoAsset.requesThumbnailImage() let previewImage = try await photoAsset.requestPreviewImage() let avAsset = try await photoAsset.requestAVAsset() let playerItem = try await photoAsset.requestPlayerItem() let livePhoto = try await photoAsset.requestLivePhoto() ``` -------------------------------- ### Get URL from Photo Asset (Swift) Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Fetches the URL for a photo asset, supporting asynchronous retrieval with optional compression. The result includes media type, URL type (local or network), and Live Photo URLs. Handles success and failure cases. ```swift let url: URL = try await photoAsset.object(compression) let urlResult: AssetURLResult = try await photoAsset.object(compression) let assetResult: AssetResult = try await photoAsset.object(compression) photoAsset.getURL(compression: compression) { result in switch result { case .success(let urlResult): switch urlResult.mediaType { case .photo: case .video: } switch urlResult.urlType { case .local: case .network: } print(urlResult.url) print(urlResult.livePhoto) case .failure(let error): print(error) } } ``` -------------------------------- ### GET /PhotoAsset/Image Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/RELEASE_NOTE.md Retrieves a processed image from a PhotoAsset with specific size and cropping requirements. ```APIDOC ## GET /PhotoAsset/Image ### Description Retrieves an image from a PhotoAsset with custom dimensions and cropping modes. ### Method GET ### Endpoint photoAsset.image(targetSize: CGSize, targetMode: PHImageContentMode) ### Parameters #### Path Parameters - **targetSize** (CGSize) - Required - The desired width and height of the image. - **targetMode** (PHImageContentMode) - Required - The cropping or scaling mode (e.g., .fill, .aspectFit). ### Request Example let image = try await photoAsset.image(targetSize: .init(width: 200, height: 200), targetMode: .fill) ### Response #### Success Response (200) - **UIImage** (Object) - The requested image object. #### Response Example { "image": "UIImageInstance" } ``` -------------------------------- ### Get UIImage from Photo Asset (Swift) Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Retrieves a UIImage from a photo asset. Supports asynchronous retrieval with optional compression and resizing. Also provides a method for obtaining the image with specific compression quality via a completion handler. ```swift let image: UIImage = try await photoAsset.object(compression) let image = try await photoAsset.image(targetSize: .init(width: 200, height: 200), targetMode: .fill) photoAsset.getImage(compressionQuality: compressionQuality) { image in print(image) } ``` -------------------------------- ### Implement GIF and Network Image Support Source: https://context7.com/silencelove/hxphotopicker/llms.txt This snippet shows how to set up image loading protocols using libraries like Kingfisher and how to instantiate network-based photo and video assets for the picker. ```swift import HXPhotoPicker import Kingfisher // Configure image view protocol PickerConfiguration.imageViewProtocol = KFImageView.self // Creating network image asset let networkImage = PhotoAsset(networkImageAsset: NetworkImageAsset( thumbnailURL: URL(string: "https://example.com/thumb.jpg")!, originalURL: URL(string: "https://example.com/original.jpg")!, imageSize: CGSize(width: 1920, height: 1080) )) // Creating network video asset let networkVideo = PhotoAsset(networkVideoAsset: NetworkVideoAsset( videoURL: URL(string: "https://example.com/video.mp4")!, duration: 30, coverImage: UIImage(named: "cover"), videoSize: CGSize(width: 1920, height: 1080) )) // Add network assets to picker var config = PickerConfiguration() let picker = PhotoPickerController(picker: config) picker.localAssetArray = [networkImage, networkVideo] present(picker, animated: true) ``` -------------------------------- ### PhotoAsset Operations in Swift Source: https://context7.com/silencelove/hxphotopicker/llms.txt Demonstrates creating PhotoAsset instances from various sources (PHAsset, local identifier, images, videos, network assets) and retrieving media data like UIImage, URLs, thumbnails, and preview images. It also covers fetching AVAsset and PlayerItem for video assets and LivePhoto objects. ```swift import HXPhotoPicker // Creating PhotoAsset from different sources let assetFromPHAsset = PhotoAsset(asset: phAsset) let assetFromIdentifier = PhotoAsset(localIdentifier: "asset-identifier") let assetFromLocalImage = PhotoAsset(image: UIImage(named: "photo")!) let assetFromLocalVideo = PhotoAsset(localVideoAsset: LocalVideoAsset(videoURL: videoURL)) let assetFromNetworkImage = PhotoAsset(networkImageAsset: NetworkImageAsset( thumbnailURL: thumbnailURL, originalURL: originalURL )) // Getting UIImage (async/await) let image: UIImage = try await photoAsset.image() // Getting UIImage with compression let compressedImage: UIImage = try await photoAsset.image(.init(imageCompressionQuality: 0.5)) // Getting UIImage with specific size let resizedImage = try await photoAsset.image( targetSize: CGSize(width: 200, height: 200), targetMode: .fill // .fill, .fit, or .center ) // Getting URL (async/await) let url: URL = try await photoAsset.url() // Getting URL with compression parameters let urlResult: AssetURLResult = try await photoAsset.urlResult( .init( imageCompressionQuality: 0.8, videoExportParameter: VideoExportParameter(preset: .ratio_960x540, quality: 6) ) ) // Getting URL with callback photoAsset.getURL(compression: .default) { result in switch result { case .success(let urlResult): print("URL: \(urlResult.url)") print("Media type: \(urlResult.mediaType)") // .photo or .video print("URL type: \(urlResult.urlType)") // .local or .network if let livePhoto = urlResult.livePhoto { print("LivePhoto image: \(livePhoto.imageURL)") print("LivePhoto video: \(livePhoto.videoURL)") } case .failure(let error): print("Failed: \(error)") } } // Getting thumbnail image let thumbnail = try await photoAsset.requesThumbnailImage() // Getting preview image let preview = try await photoAsset.requestPreviewImage() // For video assets let avAsset = try await photoAsset.requestAVAsset() let playerItem = try await photoAsset.requestPlayerItem() // For LivePhoto let livePhoto = try await photoAsset.requestLivePhoto() ``` -------------------------------- ### Implement network image loading using SDWebImage Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md This snippet demonstrates integrating SDWebImage with HXPhotoPicker by implementing the HXImageViewProtocol. It provides functionality for loading images from URLs, handling placeholders, and managing video cover thumbnails. ```swift PickerConfiguration.imageViewProtocol = SDImageView.self public class SDImageView: SDAnimatedImageView, HXImageViewProtocol { public func setImageData(_ imageData: Data?) { guard let imageData else { return } let image = SDAnimatedImage(data: imageData) self.image = image } @discardableResult public func setImage(with resource: ImageDownloadResource, placeholder: UIImage?, options: ImageDownloadOptionsInfo?, progressHandler: ((CGFloat) -> Void)?, completionHandler: ((Result) -> Void)?) -> ImageDownloadTask? { var sdOptions: SDWebImageOptions = [] var context: [SDWebImageContextOption: Any] = [:] if let options { for option in options { switch option { case .imageProcessor(let size): let imageProcessor = SDImageResizingTransformer(size: size, scaleMode: .aspectFill) context[.imageTransformer] = imageProcessor case .onlyLoadFirstFrame: sdOptions.insert(.decodeFirstFrameOnly) case .memoryCacheExpirationExpired: sdOptions.insert(.refreshCached) case .cacheOriginalImage, .fade, .scaleFactor: break } } } sd_setImage(with: resource.downloadURL, placeholderImage: placeholder, options: sdOptions, context: context) { receivedSize, totalSize, _ in let progress = CGFloat(receivedSize) / CGFloat(totalSize) DispatchQueue.main.async { progressHandler?(progress) } } completed: { image, error, cacheType, sourceURL in if let image { completionHandler?(.success(image)) }else { if let error = error as? NSError, error.code == NSURLErrorCancelled { completionHandler?(.failure(.cancel)) return } completionHandler?(.failure(.error(error))) } } let downloadTask = ImageDownloadTask { [weak self] in self?.sd_cancelCurrentImageLoad() } return downloadTask } } ``` -------------------------------- ### Support Network Images with SDWebImage Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md This snippet demonstrates how to integrate SDWebImage for loading network images and handling video covers. It involves setting PickerConfiguration.imageViewProtocol to a custom SDImageView class and implementing methods for image loading and video thumbnail generation. ```APIDOC ## Configure SDWebImage for Network Image and Video Support ### Description This section outlines the integration of SDWebImage for loading images from network URLs and generating video cover thumbnails within HXPhotoPicker. It requires implementing a custom `SDImageView` that conforms to `HXImageViewProtocol`. ### Method Configuration & Implementation ### Endpoint N/A ### Parameters #### Path Parameters N/A #### Query Parameters N/A #### Request Body N/A ### Request Example ```swift PickerConfiguration.imageViewProtocol = SDImageView.self ``` ### Response N/A ### Code Implementation ```swift public class SDImageView: SDAnimatedImageView, HXImageViewProtocol { public func setImageData(_ imageData: Data?) { guard let imageData else { return } let image = SDAnimatedImage(data: imageData) self.image = image } @discardableResult public func setImage(with resource: ImageDownloadResource, placeholder: UIImage?, options: ImageDownloadOptionsInfo?, progressHandler: ((CGFloat) -> Void)?, completionHandler: ((Result) -> Void)?) -> ImageDownloadTask? { var sdOptions: SDWebImageOptions = [] var context: [SDWebImageContextOption: Any] = [:] if let options { for option in options { switch option { case .imageProcessor(let size): let imageProcessor = SDImageResizingTransformer(size: size, scaleMode: .aspectFill) context[.imageTransformer] = imageProcessor case .onlyLoadFirstFrame: sdOptions.insert(.decodeFirstFrameOnly) case .memoryCacheExpirationExpired: sdOptions.insert(.refreshCached) case .cacheOriginalImage, .fade, .scaleFactor: break } } } sd_setImage(with: resource.downloadURL, placeholderImage: placeholder, options: sdOptions, context: context) { receivedSize, totalSize, _ in let progress = CGFloat(receivedSize) / CGFloat(totalSize) DispatchQueue.main.async { progressHandler?(progress) } } completed: { image, error, cacheType, sourceURL in if let image { completionHandler?(.success(image)) } else { if let error = error as? NSError, error.code == NSURLErrorCancelled { completionHandler?(.failure(.cancel)) return } completionHandler?(.failure(.error(error))) } } let downloadTask = ImageDownloadTask { [weak self] in self?.sd_cancelCurrentImageLoad() } return downloadTask } @discardableResult public func setVideoCover(with url: URL, placeholder: UIImage?, completionHandler: ((Result) -> Void)?) -> ImageDownloadTask? { let cacheKey = url.absoluteString if SDImageView.isCached(forKey: cacheKey) { SDImageCache.shared.queryImage(forKey: cacheKey, options: [], context: nil) { (image, data, _) in if let image { completionHandler?(.success(image)) } else { completionHandler?(.failure(.error(nil))) } } return nil } var imageGenerator: AVAssetImageGenerator? let avAsset = PhotoTools.getVideoThumbnailImage(url: url, atTime: 0.1) { imageGenerator = $0 } completion: { _, image, _ in guard let image else { completionHandler?(.failure(.error(nil))) return } SDImageCache.shared.store(image, imageData: nil, forKey: cacheKey, cacheType: .all) { DispatchQueue.main.async { completionHandler?(.success(image)) } } } let task = ImageDownloadTask { avAsset.cancelLoading() imageGenerator?.cancelAllCGImageGeneration() } return task } } ``` ``` -------------------------------- ### Implement Photo Selection in Swift Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Demonstrates three ways to invoke the HXPhotoPicker: using async/await for direct results, configuring a PhotoPickerController instance for delegate-based control, and using completion closures. These methods allow developers to retrieve images, URLs, or asset metadata based on user selection. ```swift import HXPhotoPicker class ViewController: UIViewController { func presentPickerController() { let config = PickerConfiguration() // Method 1: async/await Task { let images: [UIImage] = try await Photo.picker(config) } // Method 2: Delegate-based let pickerController = PhotoPickerController(picker: config) pickerController.pickerDelegate = self present(pickerController, animated: true, completion: nil) // Method 3: Closure-based Photo.picker(config) { result, pickerController in // Handle selection } cancel: { pickerController in // Handle cancellation } } } extension ViewController: PhotoPickerControllerDelegate { func pickerController(_ pickerController: PhotoPickerController, didFinishSelection result: PickerResult) { // Handle completion } func pickerController(didCancel pickerController: PhotoPickerController) { // Handle cancellation } } ``` -------------------------------- ### Presenting Photo Picker with HXPhotoPicker API (Swift) Source: https://context7.com/silencelove/hxphotopicker/llms.txt Demonstrates various methods to present the HXPhotoPicker and retrieve selected media assets using both async/await (iOS 13+) and callback-based approaches. It covers fetching UIImage, URLs, and detailed asset results, along with handling user cancellation and delegate patterns. ```swift import HXPhotoPicker // Method 1: Using async/await to get UIImages directly let config = PickerConfiguration.default let images: [UIImage] = try await Photo.picker(config) // Method 2: Using async/await to get URLs let urls: [URL] = try await Photo.picker(config) // Method 3: Using async/await to get detailed URL results with metadata let urlResults: [AssetURLResult] = try await Photo.picker(config) // Method 4: Using callback-based approach Photo.picker(config) { result, pickerController in // result.photoAssets - array of selected PhotoAsset objects // result.isOriginal - whether original image quality was selected result.getImage { image, photoAsset, index in if let image = image { print("Got image at index \(index): \(image.size)") } } completionHandler: { images in print("All images: \(images.count)") } } cancel: { pickerController in print("User cancelled selection") } // Method 5: Using PhotoPickerController directly with delegate let pickerController = PhotoPickerController(picker: config) pickerController.pickerDelegate = self pickerController.selectedAssetArray = previouslySelectedAssets pickerController.isOriginal = true present(pickerController, animated: true) ``` -------------------------------- ### Retrieve Custom Sized Images from PhotoAsset Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/RELEASE_NOTE.md Demonstrates how to request a specific image size and crop mode from a PhotoAsset using the async/await pattern. ```Swift /// targetSize: specify imageSize /// targetMode: crop mode let image = try await photoAsset.image(targetSize: .init(width: 200, height: 200), targetMode: .fill) ``` -------------------------------- ### Configure Camera Settings in HXPhotoPicker Source: https://context7.com/silencelove/hxphotopicker/llms.txt This snippet demonstrates how to initialize and customize the CameraConfiguration object. It covers resolution, flash modes, recording constraints, and editor integration. ```swift import HXPhotoPicker var cameraConfig = CameraConfiguration() // Camera settings cameraConfig.sessionPreset = .hd1280x720 cameraConfig.aspectRatio = ._9x16 cameraConfig.position = .back cameraConfig.flashMode = .auto // Recording settings cameraConfig.videoMaximumDuration = 60 cameraConfig.videoMinimumDuration = 1 cameraConfig.videoMaxZoomScale = 6 cameraConfig.takePhotoMode = .press // Appearance cameraConfig.tintColor = .systemBlue cameraConfig.focusColor = .systemBlue cameraConfig.prefersStatusBarHidden = true // Save to system album cameraConfig.isSaveSystemAlbum = true cameraConfig.saveSystemAlbumType = .displayName // Editor integration cameraConfig.allowsEditing = true cameraConfig.editor = EditorConfiguration() // Location tracking cameraConfig.allowLocation = true // Video codec cameraConfig.videoCodecType = .h264 ``` -------------------------------- ### Request Media Assets from PhotoAsset Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/RELEASE_NOTE.md Shows how to retrieve various media types from a PhotoAsset, including thumbnails, preview images, AV assets, player items, and Live Photos. ```Swift let thumImage = try await photoAsset.requesThumbnailImage() let previewImage = try await photoAsset.requestPreviewImage() let avAsset = try await photoAsset.requestAVAsset() let playerItem = try await photoAsset.requestPlayerItem() let livePhoto = try await photoAsset.requestLivePhoto() ``` -------------------------------- ### Configuring HXPhotoPicker Behavior and Appearance (Swift) Source: https://context7.com/silencelove/hxphotopicker/llms.txt Shows how to customize the HXPhotoPicker using the PickerConfiguration class. Options include setting theme colors, defining selectable media types, limiting selection counts, constraining video duration and file sizes, and adjusting appearance styles and language. ```swift import HXPhotoPicker // Create a custom configuration var config = PickerConfiguration() // Set theme color config.themeColor = .systemBlue // Configure selection options config.selectOptions = [.photo, .video, .gifPhoto, .livePhoto] // Media types to show config.selectMode = .multiple // .single or .multiple config.allowSelectedTogether = true // Mix photos and videos config.maximumSelectedCount = 9 // Max total selections config.maximumSelectedPhotoCount = 6 // Max photos config.maximumSelectedVideoCount = 3 // Max videos // Video duration constraints config.maximumSelectedVideoDuration = 60 // Max video duration in seconds config.minimumSelectedVideoDuration = 3 // Min video duration in seconds // File size constraints (in bytes: 1000000 = 1MB) config.maximumSelectedPhotoFileSize = 10000000 // 10MB max photo size config.maximumSelectedVideoFileSize = 50000000 // 50MB max video size // Album display mode config.albumShowMode = .popup // .normal (list) or .popup (dropdown) // Appearance config.appearanceStyle = .varied // .varied, .normal, .dark config.languageType = .english // .system, .english, .simplifiedChinese, etc. // Navigation customization config.navigationTitleColor = .black config.navigationTintColor = .systemBlue config.statusBarStyle = .default // Use preset configurations let wechatConfig = PickerConfiguration.default // WeChat-style config let redBookConfig = PickerConfiguration.redBook // RedBook-style config ``` -------------------------------- ### Download and Cache Image with HxPhotoPicker (Swift) Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Handles image downloading using ImageDownloader, processes it with DefaultImageProcessor, and caches it using ImageCache. Supports progress updates and completion handlers for success or failure. It also manages download tasks and provides methods for animation control and cache management. ```swift let task = ImageDownloader.default.downloadImage(with: resource.downloadURL, options: kfOptions) { receivedSize, totalSize in let progress = CGFloat(receivedSize) / CGFloat(totalSize) progressHandler?(progress) } completionHandler: { switch $0 { case .success(let value): DispatchQueue.global().async { if let gifImage = DefaultImageProcessor.default.process( item: .data(value.originalData), options: .init([]) ) { ImageCache.default.store( gifImage, original: value.originalData, forKey: key ) DispatchQueue.main.async { completionHandler?(.success(.init( imageData: value.originalData))) } return } ImageCache.default.store( value.image, original: value.originalData, forKey: key ) DispatchQueue.main.async { completionHandler?(.success(.init(image: value.image))) } } case .failure(let error): completionHandler?(.failure(.error(error))) } } let downloadTask = ImageDownloadTask { task?.cancel() } return downloadTask ``` -------------------------------- ### Download and Cache Images with SDWebImage Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Downloads an image from a resource URL with optional resizing and progress tracking. It checks the local cache first before initiating a network request and handles GIF animation storage. ```swift public static func download(with resource: ImageDownloadResource, options: ImageDownloadOptionsInfo?, progressHandler: ((CGFloat) -> Void)?, completionHandler: ((Result) -> Void)?) -> ImageDownloadTask? { // Implementation details for SDWebImage integration let operation = SDWebImageDownloader.shared.downloadImage(with: resource.downloadURL, ...) return ImageDownloadTask { operation?.cancel() } } ``` -------------------------------- ### Set Image with Kingfisher Options Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Configures and initiates an image download task using Kingfisher. It maps custom options to Kingfisher-specific configurations and provides progress and completion callbacks. ```Swift public func setImage(with resource: ImageDownloadResource, placeholder: UIImage?, options: ImageDownloadOptionsInfo?, progressHandler: ((CGFloat) -> Void)?, completionHandler: ((Result) -> Void)?) -> ImageDownloadTask? { var kfOptions: KingfisherOptionsInfo = [] if let options { for option in options { switch option { case .fade(let duration): kfOptions += [.transition(.fade(duration))] case .imageProcessor(let size): kfOptions += [.processor(DownsamplingImageProcessor(size: size))] case .onlyLoadFirstFrame: kfOptions += [.onlyLoadFirstFrame] case .cacheOriginalImage: kfOptions += [.cacheOriginalImage] case .memoryCacheExpirationExpired: kfOptions += [.memoryCacheExpiration(.expired)] case .scaleFactor(let scale): kfOptions += [.scaleFactor(scale)] } } } let imageResource = Kingfisher.ImageResource(downloadURL: resource.downloadURL, cacheKey: resource.cacheKey) let task = kf.setImage(with: imageResource, placeholder: placeholder, options: kfOptions) { receivedSize, totalSize in progressHandler?(CGFloat(receivedSize) / CGFloat(totalSize)) } completionHandler: { result in switch result { case .success(let res): completionHandler?(.success(res.image)) case .failure(let error): completionHandler?(.failure(error.isTaskCancelled ? .cancel : .error(error))) } } return ImageDownloadTask { task?.cancel() } } ``` -------------------------------- ### setVideoCover(with:placeholder:completionHandler:) Source: https://github.com/silencelove/hxphotopicker/blob/master/README.md Extracts and sets a cover image from a video URL using AVAssetImageDataProvider. ```APIDOC ## METHOD setVideoCover ### Description Extracts a frame from a video asset at a specific time and sets it as the image. ### Method Swift Method ### Parameters - **url** (URL) - Required - The local or remote URL of the video. - **placeholder** (UIImage) - Optional - Image to show while processing. - **completionHandler** (Closure) - Optional - Callback for the final result. ### Response - **ImageDownloadTask** - Returns a task object that can be used to cancel the process. ``` -------------------------------- ### setImage(with:placeholder:options:progressHandler:completionHandler:) Source: https://github.com/silencelove/hxphotopicker/blob/master/README.md Downloads and sets an image to a view with support for various processing options like downsampling and transitions. ```APIDOC ## METHOD setImage ### Description Downloads an image from a resource and applies it to the target view with optional processing and progress tracking. ### Method Swift Method ### Parameters #### Path Parameters - **resource** (ImageDownloadResource) - Required - The resource containing the download URL and cache key. - **placeholder** (UIImage) - Optional - Image to show while loading. - **options** (ImageDownloadOptionsInfo) - Optional - Configuration for image processing (fade, downsampling, etc.). - **progressHandler** (Closure) - Optional - Callback for download progress. - **completionHandler** (Closure) - Optional - Callback for the final result. ### Response - **ImageDownloadTask** - Returns a task object that can be used to cancel the download. ``` -------------------------------- ### Integrate Kingfisher Image View Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Implements the HXImageViewProtocol using Kingfisher's AnimatedImageView to support advanced image rendering and caching within the picker. ```swift PickerConfiguration.imageViewProtocol = KFImageView.self public class KFImageView: AnimatedImageView, HXImageViewProtocol { public func setImageData(_ imageData: Data?) { // Implementation for setting image data } } ``` -------------------------------- ### Download and Cache Images with SDWebImage Source: https://github.com/silencelove/hxphotopicker/blob/master/README.md Downloads an image from a given URL using SDWebImage, supporting custom processing options and progress tracking. It checks the cache first and returns the cached image if available, otherwise performs a network request and stores the result. ```swift public static func download(with resource: ImageDownloadResource, options: ImageDownloadOptionsInfo?, progressHandler: ((CGFloat) -> Void)?, completionHandler: ((Result) -> Void)?) -> ImageDownloadTask? { var sdOptions: SDWebImageDownloaderOptions = [] var context: [SDWebImageContextOption: Any] = [:] if let options { for option in options { switch option { case .imageProcessor(let size): let imageProcessor = SDImageResizingTransformer(size: size, scaleMode: .aspectFill) context[.imageTransformer] = imageProcessor case .onlyLoadFirstFrame: sdOptions.insert(.decodeFirstFrameOnly) default: break } } } let key = resource.cacheKey if SDImageView.isCached(forKey: key) { SDImageCache.shared.queryImage(forKey: key, options: [], context: nil) { (image, data, _) in if let data = data { completionHandler?(.success(.init(imageData: data))) } else if let image = image as? SDAnimatedImage, let data = image.animatedImageData { completionHandler?(.success(.init(imageData: data))) } else if let image { completionHandler?(.success(.init(image: image))) } else { completionHandler?(.failure(.error(nil))) } } return nil } let operation = SDWebImageDownloader.shared.downloadImage(with: resource.downloadURL, options: sdOptions, context: context, progress: { receivedSize, totalSize, _ in let progress = CGFloat(receivedSize) / CGFloat(totalSize) DispatchQueue.main.async { progressHandler?(progress) } }, completed: { image, data, error, finished in guard let data = data, finished, error == nil else { completionHandler?(.failure(.error(error))) return } DispatchQueue.global().async { let format = NSData.sd_imageFormat(forImageData: data) if format == SDImageFormat.GIF, let gifImage = SDAnimatedImage(data: data) { SDImageCache.shared.store(gifImage, imageData: data, forKey: key, options: [], context: nil, cacheType: .all) { DispatchQueue.main.async { completionHandler?(.success(.init(imageData: data))) } } return } if let image = image { SDImageCache.shared.store(image, imageData: data, forKey: key, options: [], context: nil, cacheType: .all) { DispatchQueue.main.async { completionHandler?(.success(.init(image: image))) } } } } }) return ImageDownloadTask { operation?.cancel() } } ``` -------------------------------- ### Download Image with Kingfisher Options Source: https://github.com/silencelove/hxphotopicker/blob/master/README.md Downloads an image from a given resource URL with customizable options like fade transitions, image processing, caching, and scale factors. It supports progress and completion handlers. Dependencies include Kingfisher and ImageDownloadResource. ```swift @discardableResult public func setImage(with resource: ImageDownloadResource, placeholder: UIImage?, options: ImageDownloadOptionsInfo?, progressHandler: ((CGFloat) -> Void)?, completionHandler: ((Result) -> Void)?) -> ImageDownloadTask? { var kfOptions: KingfisherOptionsInfo = [] if let options { for option in options { switch option { case .fade(let duration): kfOptions += [.transition(.fade(duration))] case .imageProcessor(let size): let imageProcessor = DownsamplingImageProcessor(size: size) kfOptions += [.processor(imageProcessor)] case .onlyLoadFirstFrame: kfOptions += [.onlyLoadFirstFrame] case .cacheOriginalImage: kfOptions += [.cacheOriginalImage] case .memoryCacheExpirationExpired: kfOptions += [.memoryCacheExpiration(.expired)] case .scaleFactor(let scale): kfOptions += [.scaleFactor(scale)] } } } let imageResource = Kingfisher.ImageResource(downloadURL: resource.downloadURL, cacheKey: resource.cacheKey) if let indicatorColor = resource.indicatorColor { kf.indicatorType = .activity (kf.indicator?.view as? UIActivityIndicatorView)?.color = indicatorColor } let task = kf.setImage(with: imageResource, placeholder: placeholder, options: kfOptions) { receivedSize, totalSize in progressHandler?(CGFloat(receivedSize) / CGFloat(totalSize)) } completionHandler: { switch $0 { case .success(let result): completionHandler?(.success(result.image)) case .failure(let error): completionHandler?(.failure(error.isTaskCancelled ? .cancel : .error(error))) } } let downloadTask = ImageDownloadTask { task?.cancel() } return downloadTask } ``` -------------------------------- ### download Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Static utility to download images or retrieve them from cache. ```APIDOC ## download ### Description Static method to download an image or retrieve it from the local cache. Returns the image or GIF data upon completion. ### Method Static Method ### Parameters - **resource** (ImageDownloadResource) - Required - The resource to download. - **options** (ImageDownloadOptionsInfo?) - Optional - Processing options. - **progressHandler** (Closure) - Optional - Progress callback. - **completionHandler** (Closure) - Optional - Callback for result (Result). ### Response - **ImageDownloadTask** - Returns a task object that allows cancellation of the download. ``` -------------------------------- ### Cache Management Utilities in HxPhotoPicker (Swift) Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Offers static utility functions for interacting with the image cache. This includes retrieving cache keys, cache paths, checking if an item is cached, and retrieving images from memory or disk cache. ```swift public static func getCacheKey(forURL url: URL) -> String { url.cacheKey } public static func getCachePath(forKey key: String) -> String { ImageCache.default.cachePath(forKey: key) } public static func isCached(forKey key: String) -> Bool { ImageCache.default.isCached(forKey: key) } public static func getInMemoryCacheImage(forKey key: String) -> UIImage? { ImageCache.default.retrieveImageInMemoryCache(forKey: key) } public static func getCacheImage(forKey key: String, completionHandler: ((UIImage?) -> Void)?) { ImageCache.default.retrieveImage(forKey: key, options: []) { switch $0 { case .success(let result): completionHandler?(result.image) case .failure: completionHandler?(nil) } } } ``` -------------------------------- ### Photo Picker API Source: https://context7.com/silencelove/hxphotopicker/llms.txt Provides static methods to present the photo picker and retrieve selected media assets using both async/await and callback patterns. ```APIDOC ## Photo Picker API ### Description The Photo class provides static methods to present the photo picker and retrieve selected media assets. It supports both async/await patterns (iOS 13+) and callback-based approaches for selecting photos, videos, and mixed media content. ### Method Static methods on the `Photo` class. ### Endpoint N/A (Local library functionality) ### Parameters - **config** (PickerConfiguration) - Required - Configuration for the photo picker. ### Request Example ```swift import HXPhotoPicker // Method 1: Using async/await to get UIImages directly let config = PickerConfiguration.default let images: [UIImage] = try await Photo.picker(config) // Method 4: Using callback-based approach Photo.picker(config) { result, pickerController in // result.photoAssets - array of selected PhotoAsset objects // result.isOriginal - whether original image quality was selected result.getImage { image, photoAsset, index in if let image = image { print("Got image at index \(index): \(image.size)") } } completionHandler: { images in print("All images: \(images.count)") } } cancel: { pickerController in print("User cancelled selection") } ``` ### Response #### Success Response - **images** ([UIImage]) - An array of selected UIImage objects. - **urls** ([URL]) - An array of URLs for the selected media. - **urlResults** ([AssetURLResult]) - An array of detailed URL results with metadata. - **result** (PickerResult) - Contains selected assets and original status in callback. #### Response Example ```json { "images": [ "UIImage data...", "UIImage data..." ], "urls": [ "file:///path/to/image1.jpg", "file:///path/to/video1.mp4" ], "urlResults": [ { "url": "file:///path/to/image1.jpg", "asset": "..." } ], "result": { "photoAssets": [ "PhotoAsset object..." ], "isOriginal": false } } ``` ``` -------------------------------- ### Configure Custom Photo Toolbar Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/RELEASE_NOTE.md Implement the PhotoToolBar protocol to customize the bottom view of the photo list and preview interface. Assign the implementation to the photoToolbar property of the configuration class. ```swift class MyCustomToolbar: PhotoToolBar { // Implement required protocol methods here } let config = PickerConfiguration() config.photoToolbar = MyCustomToolbar() ``` -------------------------------- ### Configure HXPhotoPicker Editor Settings Source: https://context7.com/silencelove/hxphotopicker/llms.txt Customize the photo and video editor's tools, appearance, and behavior. This includes settings for brush, crop, filters, text, mosaic, and music options. It allows for fine-tuning of default tools, quality, aspect ratios, and available functionalities. ```swift import HXPhotoPicker var editorConfig = EditorConfiguration() // Photo editing settings editorConfig.photo.defaultSelectedToolOption = .graffiti // Default tool on launch editorConfig.photo.filterScale = 0.5 // Filter preview quality // Video editing settings editorConfig.video.preset = .ratio_960x540 // Export resolution editorConfig.video.quality = 6 // Export quality [0-10] editorConfig.video.isAutoPlay = true editorConfig.video.defaultSelectedToolOption = .time // Default to time trimming // Video crop time settings editorConfig.video.cropTime.maximumTime = 60 // Max duration editorConfig.video.cropTime.minimumTime = 3 // Min duration // Brush settings editorConfig.brush.colors = PhotoTools.defaultColors() editorConfig.brush.defaultColorIndex = 2 editorConfig.brush.lineWidth = 5 editorConfig.brush.maximumLinewidth = 20 editorConfig.brush.minimumLinewidth = 2 editorConfig.brush.showSlider = true // Crop settings editorConfig.cropSize.isRoundCrop = false // Enable circular crop editorConfig.cropSize.isFixedRatio = false // Lock aspect ratio editorConfig.cropSize.aspectRatio = CGSize(width: 1, height: 1) // Default ratio editorConfig.cropSize.aspectRatios = [ .init(title: .custom("Original"), ratio: CGSize(width: -1, height: -1)), .init(title: .custom("Free"), ratio: .zero), .init(title: .custom("1:1"), ratio: CGSize(width: 1, height: 1)), .init(title: .custom("16:9"), ratio: CGSize(width: 16, height: 9)), .init(title: .custom("4:3"), ratio: CGSize(width: 4, height: 3)) ] // Text settings editorConfig.text.colors = PhotoTools.defaultColors() editorConfig.text.font = .boldSystemFont(ofSize: 25) editorConfig.text.maximumLimitTextLength = 100 // 0 = no limit // Mosaic settings editorConfig.mosaic.mosaicWidth = 20 editorConfig.mosaic.mosaiclineWidth = 25 editorConfig.mosaic.smearWidth = 30 // Tool view configuration (customize available tools) editorConfig.toolsView = .init(toolOptions: [ .init(imageType: .imageResource.editor.tools.graffiti, type: .graffiti), .init(imageType: .imageResource.editor.tools.chartlet, type: .chartlet), .init(imageType: .imageResource.editor.tools.text, type: .text), .init(imageType: .imageResource.editor.tools.cropSize, type: .cropSize), .init(imageType: .imageResource.editor.tools.mosaic, type: .mosaic), .init(imageType: .imageResource.editor.tools.filter, type: .filter) ]) // Music configuration for video editor editorConfig.video.music.showSearch = true editorConfig.video.music.autoPlayWhenScrollingStops = true editorConfig.video.music.infos = [ VideoEditorMusicInfo(audioURL: musicURL, lrc: lyricsString) ] ``` -------------------------------- ### Picker Configuration Source: https://context7.com/silencelove/hxphotopicker/llms.txt Provides extensive options to customize the photo picker's behavior, appearance, and selection constraints. ```APIDOC ## Picker Configuration ### Description `PickerConfiguration` provides extensive options to customize the photo picker's behavior, appearance, and selection constraints. Configure media types, selection limits, UI appearance, and album display modes. ### Method Initialization and modification of `PickerConfiguration` struct. ### Endpoint N/A (Local library functionality) ### Parameters - **themeColor** (Color) - Sets the primary theme color for the picker UI. - **selectOptions** ([SelectOption]) - Defines the types of media that can be selected (e.g., photo, video, GIF, Live Photo). - **selectMode** (SelectMode) - Determines if single or multiple selections are allowed. - **allowSelectedTogether** (Bool) - Allows mixing photos and videos in a single selection. - **maximumSelectedCount** (Int) - The maximum number of total media assets that can be selected. - **maximumSelectedPhotoCount** (Int) - The maximum number of photos that can be selected. - **maximumSelectedVideoCount** (Int) - The maximum number of videos that can be selected. - **maximumSelectedVideoDuration** (Double) - The maximum duration for selected videos in seconds. - **minimumSelectedVideoDuration** (Double) - The minimum duration for selected videos in seconds. - **maximumSelectedPhotoFileSize** (Int) - The maximum file size for selected photos in bytes. - **maximumSelectedVideoFileSize** (Int) - The maximum file size for selected videos in bytes. - **albumShowMode** (AlbumShowMode) - Configures how albums are displayed (e.g., `.popup` for dropdown, `.normal` for list). - **appearanceStyle** (AppearanceStyle) - Sets the UI appearance style (e.g., `.varied`, `.normal`, `.dark`). - **languageType** (LanguageType) - Specifies the language for the picker's UI. - **navigationTitleColor** (Color) - Customizes the color of the navigation bar title. - **navigationTintColor** (Color) - Customizes the tint color of navigation bar items. - **statusBarStyle** (UIStatusBarStyle) - Sets the status bar style. ### Request Example ```swift import HXPhotoPicker // Create a custom configuration var config = PickerConfiguration() // Set theme color config.themeColor = .systemBlue // Configure selection options config.selectOptions = [.photo, .video, .gifPhoto, .livePhoto] config.selectMode = .multiple config.allowSelectedTogether = true config.maximumSelectedCount = 9 config.maximumSelectedPhotoCount = 6 config.maximumSelectedVideoCount = 3 // Video duration constraints config.maximumSelectedVideoDuration = 60 config.minimumSelectedVideoDuration = 3 // File size constraints (in bytes: 1000000 = 1MB) config.maximumSelectedPhotoFileSize = 10000000 config.maximumSelectedVideoFileSize = 50000000 // Album display mode config.albumShowMode = .popup // Appearance config.appearanceStyle = .varied config.languageType = .english // Navigation customization config.navigationTitleColor = .black config.navigationTintColor = .systemBlue config.statusBarStyle = .default // Use preset configurations let wechatConfig = PickerConfiguration.default let redBookConfig = PickerConfiguration.redBook ``` ### Response N/A (Configuration is applied to the picker) #### Response Example N/A ``` -------------------------------- ### Manage Image Cache Operations Source: https://github.com/silencelove/hxphotopicker/blob/master/Documentation/README_EN.md Provides utility methods to retrieve cache keys, paths, and check for existence of cached images. Supports both memory and disk cache queries. ```swift public static func getCacheKey(forURL url: URL) -> String { SDWebImageManager.shared.cacheKey(for: url) ?? "" } public static func isCached(forKey key: String) -> Bool { FileManager.default.fileExists(atPath: getCachePath(forKey: key)) } public static func getInMemoryCacheImage(forKey key: String) -> UIImage? { SDImageCache.shared.imageFromMemoryCache(forKey: key) } ``` -------------------------------- ### Configure Kingfisher Image View Source: https://github.com/silencelove/hxphotopicker/blob/master/README.md Sets the global image view protocol to use Kingfisher's implementation, allowing the library to use Kingfisher for image rendering. ```swift PickerConfiguration.imageViewProtocol = KFImageView.self public class KFImageView: AnimatedImageView, HXImageViewProtocol { public func setImageData(_ imageData: Data?) { // Implementation details } } ```