HXPhotoPicker Documentation

repository·master·Indexed 25 days ago

https://github.com/silencelove/hxphotopicker

A feature-rich media picker for iOS, iPadOS, and Mac Catalyst supporting photos, videos, GIFs, and Live Photos. It includes support for iCloud and network resources, multi-selection, and advanced built-in editing tools for both images and videos. The library supports async/await, delegate patterns, and integrates with SwiftyGif, SDWebImage, and Kingfisher for extended image support.

Tokens
3.8K
Snippets
5
Records
11
Agent score
84%

What's inside HXPhotoPicker

  1. Overview of HXPhotoPicker features

    master

    HXPhotoPicker is a comprehensive photo and video picker for iOS, iPadOS, and Mac Catalyst. It supports selecting various media types and includes built-in editing capabilities.

    Key Features

    • Media Support: Photos, GIFs, Live Photos, and Videos.
    • Resource Types: Supports local resources and network resources (Photos and Videos), including iCloud downloads.
    • UI/UX: Supports Light/Dark/Auto/Custom themes, multi-selection, mixed content selection, gesture-based navigation, and sliding selection. Can be presented as a standalone list or a pop-up.
    • Image Editing: Includes doodling, stickers, text, cropping, arbitrary rotation, custom masks, mosaic, adjustments, and filters. Supports GIFs and network resources.
    • Video Editing: Includes doodling, stickers (supports GIFs), text, background music (supports lyrics/subtitles), duration/size cropping, arbitrary rotation, custom masks, adjustments, and filters. Supports network resources.
    • Internationalization: Supports multiple languages including Simplified/Traditional Chinese, English, Japanese, Korean, Thai, Indonesian, Vietnamese, Russian, German, French, and Arabic.
  2. Install HXPhotoPicker via Swift Package Manager

    master

    Add the following dependency to your Package.swift file. Note that Xcode 13.0 or higher is required to support resource files and localization.

    dependencies: [
        .package(url: "https://github.com/SilenceLove/HXPhotoPicker.git", .upToNextMajor(from: "5.0.5"))
    ]
  3. Install HXPhotoPicker via CocoaPods

    master

    Add the desired pod to your Podfile. You can choose specific subspecs to reduce binary size or add support for GIF and network images.

    Core Pods:

    • HXPhotoPicker: Default (iOS 10.0+, does not support GIF/network images by default).
    • HXPhotoPicker/Picker: Only the picker component.
    • HXPhotoPicker/Editor: Only the editor component.
    • HXPhotoPicker/Camera: Only the camera component.
    • HXPhotoPicker/Camera/Lite: Camera without location support.
    • HXPhotoPicker/NoLocation: Camera without location support.
    • HXPhotoPickerObjC: For Objective-C projects (versions below v4.0).

    Image Support Pods:

    • HXPhotoPicker/SwiftyGif: Load GIF images using SwiftyGif.
    • HXPhotoPicker/SDWebImage: Load GIF/network images using SDWebImage.
    • HXPhotoPicker/Kingfisher: Load GIF/network images using Kingfisher v6.0.0.
    /// iOS 10.0+ 默认不支持GIF和网络图片
    pod 'HXPhotoPicker'
    
    /// 使用`SwiftyGif`加载GIF图片
    pod 'HXPhotoPicker/SwiftyGif'
    
    /// 使用`SDWebImage`加载GIF/网络图片
    pod 'HXPhotoPicker/SDWebImage'
    
    /// 使用`Kingfisher v6.0.0`加载GIF/网络图片
    pod 'HXPhotoPicker/Kingfisher'
    
    /// 相机不包含定位功能
    pod `HXPhotoPicker/NoLocation`
    
    /// 只有选择器
    pod `HXPhotoPicker/Picker`
    
    /// 只有编辑器
    pod `HXPhotoPicker/Editor`
    
    /// 只有相机
    pod `HXPhotoPicker/Camera`
    /// 不包含定位功能
    pod `HXPhotoPicker/Camera/Lite`
    
    /// v4.0以下的ObjC版本
    pod 'HXPhotoPickerObjC'
  4. Quick Start: Present the Photo Picker

    master

    You can present the photo picker using three different methods: async/await, PhotoPickerController (delegate pattern), or a completion callback pattern.

    import HXPhotoPicker
    
    class ViewController: UIViewController, PhotoPickerControllerDelegate {
    
        func presentPickerController() {
            let config = PickerConfiguration()
                    
            // Method 1: async/await
            // Returns various types of results directly
            let images: [UIImage] = try await Photo.picker(config)
            let urls: [URL] = try await Photo.picker(config)
            let urlResult: [AssetURLResult] = try await Photo.picker(config)
            let assetResult: [AssetResult] = try await Photo.picker(config)
            
            // Or get a result object first
            let pickerResult = try await Photo.picker(config)
            let images: [UIImage] = try await pickerResult.objects()
            
            // Method 2: Delegate pattern
            let pickerController = PhotoPickerController(picker: config)
            pickerController.pickerDelegate = self
            pickerController.selectedAssetArray = selectedAssets 
            pickerController.isOriginal = isOriginal
            present(pickerController, animated: true, completion: nil)
            
            // Method 3: Completion callbacks
            Photo.picker(config) { result, pickerController in
                // result: .photoAssets (currently selected data), .isOriginal
            } cancel: { pickerController in
                // Cancelled callback
            }
        }
    
        // Delegate methods
        func pickerController(_ pickerController: PhotoPickerController, didFinishSelection result: PickerResult) {
            // Handle selection completion
            let images: [UIImage] = try await result.objects()
        }
    
        func pickerController(didCancel pickerController: PhotoPickerController) {
            // Handle cancellation
        }
    }
  5. Support GIF and Network Images via HXImageViewProtocol

    master

    To support GIFs or network images, you must implement the HXImageViewProtocol and assign the corresponding class to PickerConfiguration.imageViewProtocol.

    Supported integrations include:

    • SwiftyGif: Set PickerConfiguration.imageViewProtocol = GIFImageView.self
    • SDWebImage: Set PickerConfiguration.imageViewProtocol = SDImageView.self
    • Kingfisher (v6.0.0): Set PickerConfiguration.imageViewProtocol = KFImageView.self
  6. Configure Info.plist permissions for HXPhotoPicker

    master

    Add the following keys to your Info.plist to ensure the Picker and Camera modules function correctly:

    KeyModuleDescription
    NSPhotoLibraryUsageDescriptionPickerAllow access to album
    NSPhotoLibraryAddUsageDescriptionPickerAllow to save pictures to album
    PHPhotoLibraryPreventAutomaticLimitedAccessAlertPickerSet to YES to prevent automatic limited access alert in iOS 14+
    NSCameraUsageDescriptionCameraAllow camera
    NSMicrophoneUsageDescriptionCameraAllow microphone
  7. Quick Start: Present a Photo Picker

    master

    You can use HXPhotoPicker in three ways: using async/await with the Photo helper, using async/await with PhotoPickerController, or using a traditional delegate pattern.

    Method 1: async/await with Photo

    Use the Photo class for a streamlined async experience to get UIImage, URL, AssetURLResult, or AssetResult.

    Method 2: async/await with PhotoPickerController

    Directly call PhotoPickerController.picker(config) to get results asynchronously.

    Method 3: Delegate Pattern

    Initialize PhotoPickerController(picker: config), set the pickerDelegate, and call present(_:animated:completion:).

    import HXPhotoPicker
    
    class ViewController: UIViewController {
    
        func presentPickerController() {
            // Set configuration (e.g., WeChat theme)
            let config = PickerConfiguration.default
            
            // Method 1: async/await using `Photo`
            let images: [UIImage] = try await Photo.picker(config)
            let urls: [URL] = try await Photo.picker(config)
            let urlResult: [AssetURLResult] = try await Photo.picker(config)
            let assetResult: [AssetResult] = try await Photo.picker(config)
            
            // Method 2: async/await using `PhotoPickerController`
            let images: [UIImage] = try await PhotoPickerController.picker(config)
            
            // Method 3: Delegate Pattern
            let pickerController = PhotoPickerController(picker: config)
            pickerController.pickerDelegate = self
            pickerController.selectedAssetArray = selectedAssets 
            pickerController.isOriginal = isOriginal
            present(pickerController, animated: true, completion: nil)
            
            // Method 4: Completion Handlers
            Photo.picker(config) { result, pickerController in
                // Selection finished
            } cancel: { pickerController in
                // Selection cancelled
            }
        }
    }
    
    extension ViewController: PhotoPickerControllerDelegate {
        
        func pickerController(_ pickerController: PhotoPickerController, didFinishSelection result: PickerResult) {
            // Handle selection
            let images: [UIImage] = try await result.objects()
        }
        
        func pickerController(didCancel pickerController: PhotoPickerController) {
            // Handle cancellation
        }
    }
  8. Retrieve media from PhotoAsset

    master

    Use the PhotoAsset object to retrieve various media formats. Most methods support async/await or completion handlers.

    Get UIImage

    • photoAsset.object(compression): Returns a UIImage (or video cover). Use compression parameter to adjust quality.
    • photoAsset.image(targetSize:targetMode:): Returns a UIImage with a specific size and cropping mode.
    • photoAsset.getImage(compressionQuality:): Completion handler version.

    Get URL

    • photoAsset.object(compression): Returns a URL or AssetURLResult.
    • photoAsset.getURL(compression:): Completion handler version. AssetURLResult provides details on mediaType (.photo or .video), urlType (.local or .network), and livePhoto data.

    Other Assets

    • photoAsset.requesThumbnailImage(): Get thumbnail.
    • photoAsset.requestPreviewImage(): Get preview image.
    • photoAsset.requestAVAsset(): Get AVAsset.
    • photoAsset.requestPlayerItem(): Get AVPlayerItem.
    • photoAsset.requestLivePhoto(): Get PHLivePhoto.
    // Get UIImage (async/await)
    let image: UIImage = try await photoAsset.object(compression)
    let image = try await photoAsset.image(targetSize: .init(width: 200, height: 200), targetMode: .fill)
    
    // Get URL (async/await)
    let url: URL = try await photoAsset.object(compression)
    let urlResult: AssetURLResult = try await photoAsset.object(compression)
    
    // Get other assets
    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()
  9. Configure Info.plist permissions

    master

    Add the following keys to your Info.plist based on the modules you are using:

    KeyModuleDescription
    NSPhotoLibraryUsageDescriptionPickerPermission to access the photo library
    NSPhotoLibraryAddUsageDescriptionPickerPermission to save images to the photo library
    PHPhotoLibraryPreventAutomaticLimitedAccessAlertPickerSet to YES for iOS 14+ to disable the automatic