Swiftpack.co - Package - pinterest/PINRemoteImage

PINRemoteImage

Fast, non-deadlocking parallel image downloader and cache for iOS

CocoaPods compatible Carthage compatible Build status

PINRemoteImageManager is an image downloading, processing and caching manager. It uses the concept of download and processing tasks to ensure that even if multiple calls to download or process an image are made, it only occurs one time (unless an item is no longer in the cache). PINRemoteImageManager is backed by GCD and safe to access from multiple threads simultaneously. It ensures that images are decoded off the main thread so that animation performance isn't affected. None of its exposed methods allow for synchronous access. However, it is optimized to call completions on the calling thread if an item is in its memory cache.

PINRemoteImage supports downloading many types of files. It, of course, supports both PNGs and JPGs. It also supports decoding WebP images if Google's library is available. It even supports GIFs and Animated WebP via PINAnimatedImageView.

PINRemoteImage also has two methods to improve the experience of downloading images on slow network connections. The first is support for progressive JPGs. This isn't any old support for progressive JPGs though: PINRemoteImage adds an attractive blur to progressive scans before returning them.

Progressive JPG with Blur

PINRemoteImageCategoryManager defines a protocol which UIView subclasses can implement and provide easy access to PINRemoteImageManager's methods. There are built-in categories on UIImageView, PINAnimatedImageView and UIButton, and it's very easy to implement a new category. See [UIImageView+PINRemoteImage](https://raw.github.com/pinterest/PINRemoteImage/blob/master//Pod/Classes/Image Categories/UIImageView+PINRemoteImage.h) of the existing categories for reference.

Download an image and set it on an image view:

Objective-C

UIImageView *imageView = [[UIImageView alloc] init];
[imageView pin_setImageFromURL:[NSURL URLWithString:@"http://pinterest.com/kitten.jpg"]];

Swift

let imageView = UIImageView()
imageView.pin_setImage(from: URL(string: "https://pinterest.com/kitten.jpg")!)

Download a progressive jpeg and get attractive blurred updates:

Objective-C

UIImageView *imageView = [[UIImageView alloc] init];
[imageView setPin_updateWithProgress:YES];
[imageView pin_setImageFromURL:[NSURL URLWithString:@"http://pinterest.com/progressiveKitten.jpg"]];

Swift

let imageView = UIImageView()
imageView.pin_updateWithProgress = true
imageView.pin_setImage(from: URL(string: "https://pinterest.com/progressiveKitten.jpg")!)

Download a WebP file

Objective-C

UIImageView *imageView = [[UIImageView alloc] init];
[imageView pin_setImageFromURL:[NSURL URLWithString:@"http://pinterest.com/googleKitten.webp"]];

Swift

let imageView = UIImageView()
imageView.pin_setImage(from: URL(string: "https://pinterest.com/googleKitten.webp")!)

Download a GIF and display with PINAnimatedImageView

Objective-C

PINAnimatedImageView *animatedImageView = [[PINAnimatedImageView alloc] init];
[animatedImageView pin_setImageFromURL:[NSURL URLWithString:@"http://pinterest.com/flyingKitten.gif"]];

Swift

let animatedImageView = PINAnimatedImageView()
animatedImageView.pin_setImage(from: URL(string: "http://pinterest.com/flyingKitten.gif")!)

Download and process an image

Objective-C

UIImageView *imageView = [[UIImageView alloc] init];
[self.imageView pin_setImageFromURL:[NSURL URLWithString:@"https://i.pinimg.com/736x/5b/c6/c5/5bc6c5387ff6f104fd642f2b375efba3.jpg"] processorKey:@"rounded" processor:^UIImage *(PINRemoteImageManagerResult *result, NSUInteger *cost)
 {
     CGSize targetSize = CGSizeMake(200, 300);
     CGRect imageRect = CGRectMake(0, 0, targetSize.width, targetSize.height);
     UIGraphicsBeginImageContext(imageRect.size);
     UIBezierPath *bezierPath = [UIBezierPath bezierPathWithRoundedRect:imageRect cornerRadius:7.0];
     [bezierPath addClip];

     CGFloat sizeMultiplier = MAX(targetSize.width / result.image.size.width, targetSize.height / result.image.size.height);

     CGRect drawRect = CGRectMake(0, 0, result.image.size.width * sizeMultiplier, result.image.size.height * sizeMultiplier);
     if (CGRectGetMaxX(drawRect) > CGRectGetMaxX(imageRect)) {
         drawRect.origin.x -= (CGRectGetMaxX(drawRect) - CGRectGetMaxX(imageRect)) / 2.0;
     }
     if (CGRectGetMaxY(drawRect) > CGRectGetMaxY(imageRect)) {
         drawRect.origin.y -= (CGRectGetMaxY(drawRect) - CGRectGetMaxY(imageRect)) / 2.0;
     }

     [result.image drawInRect:drawRect];

     UIImage *processedImage = UIGraphicsGetImageFromCurrentImageContext();
     UIGraphicsEndImageContext();
     return processedImage;
 }];

Swift

let imageView = FLAnimatedImageView()
imageView.pin_setImage(from: URL(string: "https://i.pinimg.com/736x/5b/c6/c5/5bc6c5387ff6f104fd642f2b375efba3.jpg")!, processorKey: "rounded")  { (result, unsafePointer) -> UIImage? in

    guard let image = result.image else { return nil }

    let radius : CGFloat = 7.0
    let targetSize = CGSize(width: 200, height: 300)
    let imageRect = CGRect(x: 0, y: 0, width: targetSize.width, height: targetSize.height)

    UIGraphicsBeginImageContext(imageRect.size)

    let bezierPath = UIBezierPath(roundedRect: imageRect, cornerRadius: radius)
    bezierPath.addClip()

    let widthMultiplier : CGFloat = targetSize.width / image.size.width
    let heightMultiplier : CGFloat = targetSize.height / image.size.height
    let sizeMultiplier = max(widthMultiplier, heightMultiplier)

    var drawRect = CGRect(x: 0, y: 0, width: image.size.width * sizeMultiplier, height: image.size.height * sizeMultiplier)
    if (drawRect.maxX > imageRect.maxX) {
        drawRect.origin.x -= (drawRect.maxX - imageRect.maxX) / 2
    }
    if (drawRect.maxY > imageRect.maxY) {
        drawRect.origin.y -= (drawRect.maxY - imageRect.maxY) / 2
    }

    image.draw(in: drawRect)

    UIColor.red.setStroke()
    bezierPath.lineWidth = 5.0
    bezierPath.stroke()

    let ctx = UIGraphicsGetCurrentContext()
    ctx?.setBlendMode(CGBlendMode.overlay)
    ctx?.setAlpha(0.5)

    let logo = UIImage(named: "white-pinterest-logo")
    ctx?.scaleBy(x: 1.0, y: -1.0)
    ctx?.translateBy(x: 0.0, y: -drawRect.size.height)

    if let coreGraphicsImage = logo?.cgImage {
        ctx?.draw(coreGraphicsImage, in: CGRect(x: 90, y: 10, width: logo!.size.width, height: logo!.size.height))
    }

    let processedImage = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()

    return processedImage

}

Handle Authentication

Objective-C

[[PINRemoteImageManager sharedImageManager] setAuthenticationChallenge:^(NSURLSessionTask *task, NSURLAuthenticationChallenge *challenge, PINRemoteImageManagerAuthenticationChallengeCompletionHandler aCompletion) {
aCompletion(NSURLSessionAuthChallengePerformDefaultHandling, nil)];

Swift

PINRemoteImageManager.shared().setAuthenticationChallenge { (task, challenge, completion) in
  completion?(.performDefaultHandling, nil)
}

Support for high resolution images

Currently there are two ways PINRemoteImage is supporting high resolution images:

  1. If the URL contains an _2x. or an _3x. postfix it will be automatically handled by PINRemoteImage and the resulting image will be returned at the right scale.
  2. If it's not possible to provide an URL with an _2x. or _3x. postfix, you can also handle it with a completion handler:
NSURL *url = ...;
__weak UIImageView *weakImageView = self.imageView;
[self.imageView pin_setImageFromURL:url completion:^(PINRemoteImageManagerResult * _Nonnull result) {
  CGFloat scale = UIScreen.mainScreen.scale;
  if (scale > 1.0) {
    UIImage *image = result.image;
    weakImageView.image = [UIImage imageWithCGImage:image.CGImage scale:scale orientation:image.imageOrientation];
    }
}];

Set some limits

// cache is an instance of PINCache as long as you haven't overridden defaultImageCache
PINCache *cache = (PINCache *)[[PINRemoteImageManager sharedImageManager] cache];
// Max memory cost is based on number of pixels, we estimate the size of one hundred 600x600 images as our max memory image cache.
[[cache memoryCache] setCostLimit:600 * [[UIScreen mainScreen] scale] * 600 * [[UIScreen mainScreen] scale] * 100];

// ~50 MB
[[cache diskCache] setByteLimit:50 * 1024 * 1024];
// 30 days
[[cache diskCache] setAgeLimit:60 * 60 * 24 * 30];

Installation

CocoaPods

Add PINRemoteImage to your Podfile and run pod install.

If you'd like to use WebP images, add PINRemoteImage/WebP to your Podfile and run pod install.

Carthage

Add github "pinterest/PINRemoteImage" to your Cartfile . See Carthage's readme for more information on integrating Carthage-built frameworks into your project.

Manually

Download the latest tag and drag the Pod/Classes folder into your Xcode project. You must also manually link against PINCache.

Install the docs by double clicking the .docset file under docs/, or view them online at cocoadocs.org

Git Submodule

You can set up PINRemoteImage as a submodule of your repo instead of cloning and copying all the files into your repo. Add the submodule using the commands below and then follow the manual instructions above.

git submodule add https://github.com/pinterest/PINRemoteImage.git
git submodule update --init

Requirements

PINRemoteImage requires iOS 7.0 or greater.

Contact

Garrett Moon @garrettmoon Pinterest

License

Copyright 2015 Pinterest, Inc.

Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0

Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License.

Github

link
Stars: 3840

Dependencies

Used By

Total: 0

Releases

3.0.3 - 2020-10-23 18:43:39

Changelog

3.0.3 (2020-10-23)

Full Changelog

3.0.2 - 2020-10-22 21:45:43

Changelog

3.0.2 (2020-10-22)

Full Changelog

3.0.1 Xcode 12 - 2020-09-16 15:21:20

3.0.1 (2020-09-08)

Full Changelog

Merged pull requests:

  • Update PINCache in podspec #564 (garrettmoon)
  • Update PINCache and PINOperation #562 (garrettmoon)
  • Let's use the same commands we use locally. #561 (garrettmoon)
  • Ensure the example defines the macros before referencing them. #557 (bolsinga)
  • Remove the PCH file and ensure macros are defined before using #556 (bolsinga)
  • Seems that having the framework and example have the same name confuses cocoapods #555 (garrettmoon)
  • Upgrade WebP to 1.1.0 #554 (garrettmoon)
  • Conditionally call CADisplayLink method based upon iOS10 availability to remove deprecation warning #552 (bolsinga)
  • Fix typos #548 (pgrimaud)
  • Remove unused CI directory #547 (jparise)
  • PINCachedAnimatedImage: Fix retain cycles #546 (bolsinga)
  • Fix up analyze for new github CI #545 (garrettmoon)
  • Switch to GitHub Actions for CI #544 (jparise)
  • #trivial Fix performance issue caused by saving encoded image data to memory cache #539 (Naituw)
  • Update 3.0.0 change log and podspec #537 (ernestmama)
  • Fix memory cache content in README #530 (OhKanghoon)
  • Refactor remote manager task for uuid method #526 (zhongwuzw)
  • Burst Animated Image speed of frame index search #523 (zhongwuzw)
  • Set HTTPMaximumConnectionsPerHost to PINRemoteImageHTTPMaximumConnectionsPerHost only if user don't provide sessionConfiguration #516 (zhongwuzw)
  • Fixes re-downloading data corrupt for the same url #514 (zhongwuzw)

3.0.0 Finally! - 2020-01-06 23:53:12

  • [new] Add PINRemoteImageManagerConfiguration configuration object. #492 rqueue
  • [fixed] Fixes blending in animated WebP images. #507 garrettmoon
  • [fixed] Fixes support in PINAnimatedImageView for WebP animated images. #507 garrettmoon
  • [new] Exposure didCompleteTask:withError: delegate method of protocol PINURLSessionManagerDelegate. #519 zhongwuzw
  • [fixed] Fixes AnimatedImageView designated initializer not work. #512 zhongwuzw
  • [fixed] Set bpp(bits per pixel) to 32 bit for GIF. #511 zhongwuzw
  • [new] Add cancel method for PINRemoteImageManager. #509 zhongwuzw
  • [fixed] Fixes build error when using Xcode 10.2.1. #524 ANNotunzdY

Fixes galore! - 2019-02-20 19:39:47

  • [new] Allow use of NSURLCache via a custom NSURLSession #477 wiseoldduck
  • [new] Respect Cache-Control and Expires headers if the cache supports TTL. #462 wiseoldduck
  • [new] Updated to latest PINCache beta 7. #461 wiseoldduck
  • [iOS11] Fix warnings #428 Eke
  • [new / beta] Native Support for GIFs and animated WebP #453 garrettmoon
  • [new] Add support for getting NSURLSessionMetrics back. #456 garrettmoon
  • [removed] Removed support for FLAnimatedImage #453 garrettmoon
  • [new] Add support for higher frame rate devices to animated images. #417 garrettmoon
  • [fixed] Fixes non-animated GIFs being delivered as an animated image. #434 garrettmoon
  • [fixed] Fixes a bug where using PINRemoteImageBasicCache would cause images to be decoded on the main thread. #457 kgaidis
  • [cleanup] Remove unused code that supported iOS < 7. #435 Adlai-Holler
  • [cleanup] Use NS_ERROR_ENUM to improve Swift import. #440 Adlai-Holler
  • [fixed] Fixes nil session manager configuration. #460 garrettmoon
  • [fixed] Fixes deprecated -defaultImageCache not being called if overridden. 479 nguyenhuy
  • [new] Add a new API that allows a priority to be set when a new download task is scheduled. #490 nguyenhuy

3.0 beta 13: Animated WebP support / better GIF handling - 2017-10-09 16:08:04

  • [new] Support for webp and improved support for GIFs. #411 garrettmoon
  • [new] Added back tvOS support through a new target #408 jverdi
  • [refactor] Refactor out KVO on NSURLSessionTask to avoid Apple crashes. #410 garrettmoon

3.0 beta 12 - 2017-09-08 23:54:12

  • [new] Added a way to specify custom retry logic when network error happens #386
  • [new] Improve disk cache migration performance #391 chuganzy, #394 nguyenhuy
  • [new] Adds support for using cell vs. wifi in leau of speed for determing which URL to download if speed is unavailable. garrettmoon
  • [new] Uses BPS minus time to first byte for deciding which of a set of URLs to download. garrettmoon
  • [fixed] Fixes an edge case when image returned with 404 response, we now treat it as image instead of error #399 maxwang

3.0 Beta 11 - 2017-06-30 20:08:08

Beta 11 has a bunch of bug fixes as well some new features:

  • [new] PINRemoteImageManager now respects the request timeout value of session configuration. garrettmoon
  • [new] Added support for getting NSURLResponse from a PINRemoteImageManagerResult object. garrettmoon
  • [new] Updated to latest PINCache beta 5. garrettmoon
  • [fixed] Fixes a deadlock with canceling processor tasks #374 zachwaugh
  • [fixed] Fixes a deadlock in the retry system. garrettmoon
  • [fixed] Fixes a threadsafety issue in accessing callbacks. garrettmoon
  • [fixed] Fixes a crash with resumed downloads when a key is long. garrettmoon

3.0 Beta 10 - 2017-06-05 18:23:31

Beta 10 is mostly a bug fix release with one new feature:

  • [new] Added support (in iOS 10) for skipping cancelation if the estimated amount of time to complete the download is less than the average time to first byte for a host. #364 garrettmoon
  • [fixed] Fixes an issue where PINResume would assert because the server didn't return an expected content length.
  • [fixed] Fixed bytes per second on download tasks (which could affect if an image is progressively rendered) #360 garrettmoon
  • [new] Added request configuration handler to allow customizing HTTP headers per request #355 zachwaugh
  • [fixed] Moved storage of resume data to disk from memory. garrettmoon
  • [fixed] Hopefully fixes crashes occuring in PINURLSessionManager on iOS 9. garrettmoon

Beta 9: Support for resuming downloads, faster operation queue - 2017-04-05 22:04:49

Included in Beta 9 is one big feature and one big performance improvement:

  • New support for resuming canceled downloads. If you call cancelTaskWithUUID:storeResumeData: you can specify that any data already downloaded be stored in the memory cache. If you later attempt to download the image at the URL again, it will resume where it left off. (#331) Caveats:
    • Resume data is only stored in the memory cache, not the disk cache
    • Your server must support resuming downloads by responding to requests with the Accept-Range header == bytes and providing either an ETag header or a Last-Modified header.
  • Performance switch to PINOperationQueue from NSOperationQueue which turned out to take a lot of the time PINRemoteImage used on the main thread. (#338, #326, #329)

Beta 8 - 2017-02-21 17:46:19

Included in Beta 8:

  • Complete refactor of build system #317
  • Some performance improvements #285 #287 #312
  • Added ability to manually add image to cache #299
  • Fixed GIFs #302
  • Added ability to configure headers sent with requests #293
  • Added ability to automatically support @2x and @3x images #311
  • Updated to the latest PINCache #320

Beta 7 - 2016-12-06 18:49:51

Included in beta 7:

  • Fixes images sometimes being corrupted: #279
  • Fixes cache cost calculation: #278
  • Switches our CI to something more reliable: #266
  • Fixes a build error for Carthage: #273
  • Adds an option to bypass the cache: #272

3.0 Beta 6 - 2016-11-07 22:13:39

On to Beta 6!

This release contains the latest PINCache and a new pluggable cache (so you can use your own cache instead of PINCache if you wish).

Beta 5 - 2016-10-20 19:44:55

  • Fixes a nasty bug in Beta 4 which made it so alternativeRepresentationProviders were ignored!
  • Re-enables PINCache dependency in CocoaPods to un-break upstream dependencies. This will be re-enabled in the 3.0 final release.

Beta 4 - 2016-10-17 22:26:22

Includes new pluggable cache, thanks @skeeet !

Beta 3 - 2016-08-02 23:59:10

Includes PINCache 3 beta.

3.0 Beta 2 - 2016-05-03 19:46:23

[fix] Merge tvOS spec into iOS spec [#196]

3.0 beta - 2016-04-25 18:25:26

Adds progressive quality to callback - 2016-04-22 20:22:09

[new] Have PINProgressiveImage pass back the quality of the current progressive image #185

Fix invalid clearing of disk cache object. - 2016-04-13 15:20:31

  • [fixed] Images May Be Removed from Disk Cache for Not Being in Memory Cache #186

Pedantic fixes and bug squashes - 2016-03-25 16:12:36

  • [fixed] Remove disk cache call potentially on main thread #167
  • [fixed] Nullability specifiers #170
  • [fixed] Speling errorrs, unused properties and spacing #172

OS X and Carthage Fixes - 2016-03-21 00:53:04

  • [new] Slightly more performant locking #165
  • [new] Added support for pulling images synchronously from the cache #162
  • [fixed] Non-decoded images no longer cached by OS #161
  • [fixed] OS X and Carthage support #164

tvOS Support! - 2016-03-12 05:13:15

  • [new] tvOS support: #131
  • [new] added method to get image out of cache synchronously: #162
  • [fixed] undecoded images are no longer cached by OS: #161
  • [fixed] carthage support and OS X example: #160

Bitcode and bug fixes - 2016-02-23 23:59:45

  • [new] Removed explicit disabling of bitcode: #136
  • [fixed] Progressive rendering in example apps: #148
  • [fixed] Carthage compilation: #141
  • [fixed] Crash on iOS 7 when setting download priority #137
  • [fixed] Dumb test bugs! #144

OS X Support - 2016-02-11 02:22:27

Adds OS X Support and removes deprecated methods.

Carthage Support - 2015-11-03 18:28:13

Adds support for Carthage as well as a few bug fixes.

Fix Podspec issues - 2015-10-09 16:47:30

This release is meant to fix pod spec issues.

Xcode 7 Support - 2015-09-22 17:12:31

Many bug fixes and Xcode 7 support.

- 2015-08-04 18:13:33

  • Fix crash that occurred on iOS < 8.0

1.1.1 - 2015-08-03 20:51:58

This release fixes a deadlock that could occur if a task was immediately canceled after starting. Thank you @jparise!