GithubHelp home page GithubHelp logo

sdwebimage / sdwebimagephotosplugin Goto Github PK

View Code? Open in Web Editor NEW
59.0 9.0 7.0 437 KB

A SDWebImage plugin to support Photos framework image loading

License: MIT License

Ruby 3.13% Objective-C 94.82% Swift 2.05%
macos ios tvos photoslibrary objective-c cocoapods sdwebimage

sdwebimagephotosplugin's Introduction

SDWebImagePhotosPlugin

CI Status Version License Platform Carthage compatible SwiftPM compatible codecov

What it's for

SDWebImagePhotosPlugin is a plugin for the SDWebImage framework, which provides image loading support for the Photos Library.

This plugin allows you to use your familiar View Category method from SDWebImage, for loading Photos images with PHAsset or localIdentifier.

Requirements

  • iOS 9+
  • macOS 10.13+
  • tvOS 10+
  • Xcode 10+

Installation

CocoaPods

SDWebImagePhotosPlugin is available through CocoaPods. To install it, simply add the following line to your Podfile:

pod 'SDWebImagePhotosPlugin'

Carthage

SDWebImagePhotosPlugin is available through Carthage.

github "SDWebImage/SDWebImagePhotosPlugin"

Swift Package Manager (Xcode 11+)

SDWebImagePhotosPlugin is available through Swift Package Manager.

let package = Package(
    dependencies: [
        .package(url: "https://github.com/SDWebImage/SDWebImagePhotosPlugin.git", from: "1.0")
    ]
)

Usage

Important! To use this Photos Library plugin, you first need to register the photos loader to image manager.

There are two ways to register the photos loader. One is for temporarily usage (when providing URL is definitely Photos URL but not HTTP URL), and another for global support (don't need any check, supports both HTTP URL as well as Photos URL).

Use custom manager (temporarily)

You can create a custom manager for temporary usage. When you use custom manager, be sure to specify SDWebImageContextCustomManager context option with your custom manager for View Category methods.

  • Objective-C
// Assign loader to custom manager
SDWebImageManager *manager = [[SDWebImageManager alloc] initWithCache:SDImageCache.sharedImageCache loader:SDImagePhotosLoader.sharedLoader];
  • Swift
// Assign loader to custom manager
let manager = SDWebImageManager(cache: SDImageCache.shared, loader: SDImagePhotosLoader.shared)

Use loaders manager (globally)

You can replace the default manager's loader implementation using loaders manager to support both HTTP && Photos URL globally. Put these code just at the application launch time (or some time just before SDWebImageManager.sharedManager is initialized).

  • Objective-C
// Supports HTTP URL as well as Photos URL globally
SDImageLoadersManager.sharedManager.loaders = @[SDWebImageDownloader.sharedDownloader, SDImagePhotosLoader.sharedLoader];
// Replace default manager's loader implementation
SDWebImageManager.defaultImageLoader = SDImageLoadersManager.sharedManager;
  • Swift
// Supports HTTP URL as well as Photos URL globally
SDImageLoadersManager.shared.loaders = [SDWebImageDownloader.shared, SDImagePhotosLoader.shared]
// Replace default manager's loader implementation
SDWebImageManager.defaultImageLoader = SDImageLoadersManager.shared

Load Images

To start loading the Photos Library image, use the NSURL+SDWebImagePhotosPlugin to create a Photos URL and call View Category method.

  • Objective-C
// Create with `PHAsset`
PHAsset *asset;
NSURL *photosURL = asset.sd_URLRepresentation;
// The same as `[NSURL sd_URLWithAsset:asset];`
// Create with `localIdentifier`
NSString *identifier;
NSURL *potosURL = [NSURL sd_URLWithAssetLocalIdentifier:identifier];

// Load image (assume using custom manager)
[imageView sd_setImageWithURL:photosURL placeholderImage:nil context:@{SDWebImageContextCustomManager: manager}];
  • Swift
// Create with `PHAsset`
let asset: PHAsset
let photosURL = asset.sd_URLRepresentation
// The same as `NSURL.sd_URL(with: asset) as URL`
// Create with `localIdentifier`
let identifier: String
let potosURL = NSURL.sd_URL(withAssetLocalIdentifier: identifier) as URL

// Load image (assume using custom manager)
imageView.sd_setImage(with: photosURL, placeholderImage: nil, context: [.customManager: manager])

Animated Images

SDWebImagePhotosPlugin supports GIF images stored in Photos Library as well. Just use the same API as normal images to query the asset. We will query the image data and decode the animated images (compatible with UIImageView as well as SDAnimatedImageView)

Video Assets

SDWebImagePhotosPlugin supports loading Video Asset poster as well. By default, we don't allow non-image type assets, to avoid accidentally picking a wrong Asset. But you can disable this limit as well.

  • Objective-C
SDImagePhotosLoader.sharedLoader.requestImageAssetOnly = NO;
  • Swift
SDImagePhotosLoader.shared.requestImageAssetOnly = false

Then just request the PHAssets or using the fetch options, which the media type is .video.

Fetch/Request Options

To specify options like PHFetchOptions or PHImageRequestOptions for Photos Library. Either to change the correspond properties in loader, or provide a context options for each image request.

  • Objective-C
// loader-level options
// ignore iCloud Shared Album (`localIdentifier` Photos URL only)
PHFetchOptions *fetchOptions = [PHFetchOptions new];
fetchOptions.predicate = [NSPredicate predicateWithFormat:@"sourceType != %d", PHAssetSourceTypeCloudShared];
SDImagePhotosLoader.sharedLoader.fetchOptions = fetchOptions;

// request-level options
// allows iCloud Photos Library
PHImageRequestOptions *requestOptions = [PHImageRequestOptions new];
requestOptions.networkAccessAllowed = YES;
[imageView sd_setImageWithURL:photosURL placeholderImage:nil context:@{SDWebImageContextPhotosImageRequestOptions: requestOptions, SDWebImageContextCustomManager: manager}];
  • Swift
// loader-level options
// ignore iCloud Shared Album (`localIdentifier` Photos URL only)
let fetchOptions = PHFetchOptions()
fetchOptions.predicate = NSPredicate(format: "sourceType != %d", PHAssetSourceType.typeCloudShared.rawValue)
SDImagePhotosLoader.shared.fetchOptions = fetchOptions

// request-level options
// allows iCloud Photos Library
let requestOptions = PHImageRequestOptions()
requestOptions.networkAccessAllowed = true
imageView.sd_setImage(with: photosURL, placeholderImage: nil, context:[.photosImageRequestOptions: requestOptions, .customManager: manager])

Control Query Image Size

Photos taken by the iPhone camera may have a really large pixel size (4K+). So, if you want to load large Photos Library assets for rendering, you should specify target size with a limited size (for example, the size of the imageView that you are loading into).

By default, we query the target size that matches the original image's largest size (see: PHImageManagerMaximumSize), which may consume too much memory on iOS devices. There are also two built-in dynamic values SDWebImagePhotosPixelSize/SDWebImagePhotosPointSize which are suitable for some cases.

You can change the fetch image size by either using the PHImageRequestOptions.sd_targetSize, or Thumbnail Decoding via .imageThumbnailPixelSize context option.

Control query image size limit in global:

  • Objective-C
SDImagePhotosLoader.sharedLoader.imageRequestOptions.sd_targetSize = CGSizeMake(1000, 1000); // Limit 1000x1000 pixels
  • Swift
SDImagePhotosLoader.shared.imageRequestOptions.sd_targetSize = CGSize(width: 1000, height: 1000) // Limit 1000x1000 pixels

Control query image size for individual assets:

  • Objective-C
UIImageView *imageView;
PHAsset *asset;
NSURL *url = asset.sd_URLRepresentation;
[imageView.sd_setImageWithURL:url options:0 context:@{SDWebImageContextImageThumbnailPixelSize: @(imageView.bounds.size)}]; // Fetch image based on image view size
  • Swift
let imageView: UIImageView
let asset: PHAsset
let url = asset.sd_URLRepresentation
imageView.sd_setImage(with: url, context: [.imageThumbnailPixelSize : imageView.bounds.size]) // Fetch image based on image view size

Note: You can also use SDWebImageContextPhotosImageRequestOptions as shown above. But the thumbnail pixel size can be used for normal Network URL as well, which can help you to unify the logic for HTTP URL and PHAsset URL.

Tips

  1. Images from the Photos Library are already stored on the device disk, and query speed is fast enough for small resolution images, so cache storage might be unnecessary. You can use SDWebImageContextStoreCacheType with SDImageCacheTypeNone to disable cache storage, and use SDWebImageFromLoaderOnly to disable cache queries.
  2. If you use PHImageRequestOptionsDeliveryModeOpportunistic (default) to load the image, PhotosKit will return a degraded thumbnail image first and again with the full pixel image. When the image is degraded, the loader completion block will set finished = NO. However, this will not trigger the View Category completion block, and only trigger a image refresh (like progressive loading behavior for network image using SDWebImageProgressiveLoad)
  3. By default, we will prefer using Photos requestImageForAsset:targetSize:contentMode:options:resultHandler: API for normal images, using requestImageDataForAsset:options:resultHandler: for animated images like GIF asset. If you need the raw image data for further image processing, you can always pass the SDWebImageContextPhotosRequestImageData context option to force using the request data API instead. Note that when requesting data, the targetSize and contentMode options are ignored. If you need smaller image sizes, consider using Image Transformer feature from SDWebImage 5.0.

Demo

If you have some issue about usage, SDWebImagePhotosPlugin provide a demo for iOS & macOS platform. To run the demo, clone the repo and run the following command.

cd Example/
pod install
open SDWebImagePhotosPlugin.xcworkspace

After the Xcode project is opened, click Run to build and run the demo.

Author

DreamPiggy, [email protected]

License

SDWebImagePhotosPlugin is available under the MIT license. See the LICENSE file for more info.

sdwebimagephotosplugin's People

Contributors

aheze avatar bpoplauschi avatar dreampiggy avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

sdwebimagephotosplugin's Issues

reloaddata causes image flickering

In the demo project, as in mine, when you reload the collectionview, the pictures flicker, when I reload only visible cells, this does not happen, but some cells remain not updated when scrolling. Are there any ways to solve this?

Support for SDWebImage 4.X

Feature Request Description

This pod should really attempt to use the stable version of SDWebImage if possible. I cannot use this even though it would be useful because I will not update my SDWebImage dependency to a beta version.

unsupported URL

2018-09-04 18:31:24.318357+0530 [1690:202387] Task <65A83068-4467-4DBA-B035-720EBB27A59A>.<7> finished with error - code: -1002
2018-09-04 18:31:24.337494+0530 [1690:202405] Task <65A83068-4467-4DBA-B035-720EBB27A59A>.<7> load failed with error Error Domain=NSURLErrorDomain Code=-1002 "unsupported URL" UserInfo={NSLocalizedDescription=unsupported URL, NSErrorFailingURLStringKey=photos://asset/82CCD013-F7E9-461F-8F36-5E3A4FCAD6BB/L0/001, NSErrorFailingURLKey=photos://asset/82CCD013-F7E9-461F-8F36-5E3A4FCAD6BB/L0/001, _NSURLErrorRelatedURLSessionTaskErrorKey=(
"LocalDataTask <65A83068-4467-4DBA-B035-720EBB27A59A>.<7>"
), _NSURLErrorFailingURLSessionTaskErrorKey=LocalDataTask <65A83068-4467-4DBA-B035-720EBB27A59A>.<7>, NSUnderlyingError=0x281b02ac0 {Error Domain=kCFErrorDomainCFNetwork Code=-1002 "(null)"}} [-1002]

Support for URL instead of NSURL

New Feature Request Checklist

  • I have checked the current documentations or APIs and did not find a solution
  • I have searched for a similar issue in the project and found none

Feature Request Description

Currently, you make a NSURL from PHAsset like this:

// Create with `PHAsset`
let asset: PHAsset
let photosURL = NSURL.sd_URL(with: asset)

// Load image (assume using custom manager)
imageView.sd_setImage(with: photosURL, placeholderImage: nil, context: [.customManager: manager])

However, sd_setImage(with: takes a URL, not NSURL.

Screen Shot 2020-12-30 at 8 20 47 PM

I would like to be able to get a URL from PHAsset, something like this:

// Create with `PHAsset`
let asset: PHAsset
let photosURL = URL.sd_URL(with: asset) /// URL not NSURL

// Load image (assume using custom manager)
imageView.sd_setImage(with: photosURL, placeholderImage: nil, context: [.customManager: manager])

This would avoid the error, and I think URLs are safer than NSURLs.

Crashed with beta4 and beta6

Crashed with beta4 and beta6.
Example of request:

let requestOptions = PHImageRequestOptions()
requestOptions.sd_targetSize = targetSize
requestOptions.sd_contentMode = .aspectFill
requestOptions.isNetworkAccessAllowed = true

if let url = NSURL.sd_URL(with: asset) as URL? {
sd_setImage(with: url,
         placeholderImage: nil,
         context: [.photosImageRequestOptions: requestOptions,
                        .customManager: SDWebImagePhotosLoader.shared])
} else {
    sd_cancelCurrentImageLoad()
    image = nil
}

Get this crash:
crash

Carthage build failed

New Issue Checklist

  • I have read the tutorial usage
  • I have searched for a similar issue in the project and found none

Issue Info

Info Value
Platform Name ios
Platform Version 14.4
Framework Version 1.2.0
Integration Method carthage
Xcode Version Xcode 12.4
Repro rate all the time (100%)
Repro with our demo prj
Demo project link

Issue Description and Steps

Cartfile

github "SDWebImage/SDWebImage"
github "SDWebImage/SDWebImagePhotosPlugin"

log

carthage update --platform iOS --use-xcframeworks --cache-builds
*** Fetching SDWebImage
*** Fetching SDWebImagePhotosPlugin
*** Checking out SDWebImage at "5.11.1"
*** Checking out SDWebImagePhotosPlugin at "1.2.0"
*** xcodebuild output can be found in /var/folders/zr/4r0p2kpd4gg0thfj05jldkgc0000gn/T/carthage-xcodebuild.a4iK05.log
*** Valid cache found for SDWebImage, skipping build
*** No cache found for SDWebImagePhotosPlugin, building with all downstream dependencies
*** Building scheme "SDWebImagePhotosPlugin" in SDWebImagePhotosPlugin.xcodeproj
Build Failed
 Task failed with exit code 65:
 /usr/bin/xcrun xcodebuild -project /Users/venice/projects/CarthageTest/Carthage/Checkouts/SDWebImagePhotosPlugin/SDWebImagePhotosPlugin.xcodeproj -scheme SDWebImagePhotosPlugin -configuration Release -derivedDataPath /Users/venice/Library/Caches/org.carthage.CarthageKit/DerivedData/12.4_12D4e/SDWebImagePhotosPlugin/1.2.0 -sdk iphoneos ONLY_ACTIVE_ARCH=NO CODE_SIGNING_REQUIRED=NO CODE_SIGN_IDENTITY= CARTHAGE=YES archive VALIDATE_WORKSPACE=NO -archivePath /var/folders/zr/4r0p2kpd4gg0thfj05jldkgc0000gn/T/SDWebImagePhotosPlugin SKIP_INSTALL=YES GCC_INSTRUMENT_PROGRAM_FLOW_ARCS=NO CLANG_ENABLE_CODE_COVERAGE=NO STRIP_INSTALLED_PRODUCT=NO (launched in /Users/venice/projects/CarthageTest/Carthage/Checkouts/SDWebImagePhotosPlugin)

This usually indicates that project itself failed to compile. Please check the xcodebuild log for more details: /var/folders/zr/4r0p2kpd4gg0thfj05jldkgc0000gn/T/carthage-xcodebuild.a4iK05.log
✘ venice  ~/projects/CarthageTest 

Extremely high memory usage and slow scrolling

New Issue Checklist

  • I have read the tutorial usage
  • I have searched for a similar issue in the project and found none

Issue Info

Info Value
Platform Name iOS
Platform Version 14.2
Framework Version SDWebImage (5.8.3), SDWebImagePhotosPlugin (1.1.0)
Integration Method cocoapods
Xcode Version Xcode 12
Repro rate 100%
Repro with our demo prj No
Demo project link https://github.com/aheze/PhotoLoading

Issue Description and Steps

The collection view scrolls choppily, and the memory goes over 1 gb, depending on how many photos you have. It sometimes also crashes due to Terminated due to memory error.

Screen Shot 2020-12-30 at 8 07 04 PM

I followed the example project (it's in Objective-C so I probably misread some things), first doing this inside viewDidLoad():

//Supports HTTP URL as well as Photos URL globally
SDImageLoadersManager.shared.loaders = [SDWebImageDownloader.shared, SDImagePhotosLoader.shared]

// Replace default manager's loader implementation
SDWebImageManager.defaultImageLoader = SDImageLoadersManager.shared

let options = PHImageRequestOptions()
options.sd_targetSize = CGSize(width: 500, height: 500) /// make sure don't load too big
SDImagePhotosLoader.shared.imageRequestOptions = options

Instead of an array of NSURL I used an array of PHAsset:

var allPhotos: PHFetchResult<PHAsset>? = nil
...
PHPhotoLibrary.requestAuthorization { (status) in /// request access inside ViewDidLoad
    if status == .authorized {
        let fetchOptions = PHFetchOptions()
        self.allPhotos = PHAsset.fetchAssets(with: .image, options: fetchOptions)
        DispatchQueue.main.async {
            self.collectionView.reloadData() /// reload collectionview once done
        }
    }
}

And this is my cellForRowAt. I make the NSURL here.

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
  let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseID, for: indexPath) as! CollectionViewCell
  
  let asset = allPhotos![indexPath.item]
  let photosURL = NSURL.sd_URL(with: asset)
  cell.imageView.sd_setImage(with: photosURL as URL?, placeholderImage: nil, options: SDWebImageOptions.fromLoaderOnly)
  return cell
}

My full code is all in ViewController.swift (63 lines). What am I doing wrong? Thanks for any help!

Request completion block

Hi! I wonder if it is possible to get completion block after photo loading was completed for following method:
imageView.sd_setImage(with: photoURL, placeholderImage: nil, context [.photosImageRequestOptions: requestOptions])
Thanks in advance!

Only support image

Only support PHAssetMediaTypeImage
pls support PHAssetMediaTypeVideo too

Does not load image in the SDAnimatedImageView (intermittent issue)

Since Photos Library image is already stored on the device disk. And query speed is fast enough for small resolution image. You can use SDWebImageContextStoreCacheType with SDImageCacheTypeNone to disable cache storage. And use SDWebImageFromLoaderOnly to disable cache query.

This does not load image sometimes in the SDAnimatedImageView.

Is it possible to have SDWebImagePhotosPlugin work with SDWebImage v.5.10.X using SPM?

New Feature Request Checklist

  • I have checked the current documentations or APIs and does not find a solution
  • I have searched for a similar issue in the project and found none
    I seem to be able to only make it work with 5.9.X. You run into the dreaded
    "The package product 'iOSAnyPackage' requires minimum platform version 9.0 for the iOS platform, but this target supports 8.0" error outlined here https://forums.swift.org/t/xcode12-minimum-deployment-target-and-spm/40467 when you update your package.
    There seem to be ways to do this using CocoaPods, but I am having trouble finding anything useful when working with SPM.

Feature Request Description

Please fill in the detailed description about feature request, including the feature use case (what you need) and the solution you want (like usage, demo code, ...)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. 📊📈🎉

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.