Movatterモバイル変換


[0]ホーム

URL:


Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Sign up
Appearance settings

5.0 Migration guide

DreamPiggy edited this pageOct 22, 2021 ·24 revisions

SDWebImage 5.0 Migration Guide

SDWebImage 5.0 is the latest major release of SDWebImage, a top library for downloading and caching images.As a major release, followingSemantic Versioning conventions, 5.0 introduces several API-breaking changes with its new architecture.

This guide is provided in order to ease the transition of existing applications using SDWebImage 4.X to the latest APIs, as well as explain the design and structure of new and changed functionality.

Requirements: iOS 8, Mac OS X 10.10, watchOS 2, tvOS 9, Xcode 9

SDWebImage 5.0 officially supports iOS 8 and later, Mac OS X 10.10 and later, watchOS 2 and later and tvOS 9 and later.It needs Xcode 9 or later to be able to build everything properly.

For targeting previous versions of the SDKs, checkREADME - Backwards compatibility.

Migration

Using the view categories brings no change from 4.x to 5.0.

Objective-C:

[imageViewsd_setImageWithURL:urlplaceholderImage:placeholderImage];

Swift:

imageView.sd_setImage(with: url, placeholderImage: placeholder)

However, all view categories in 5.0 introduce a new extra arg calledSDWebImageContext. This param can hold anything, as opposed to the previousSDWebImageOptions enum limitations. This gives developers advanced control for the behavior of image loading (cache, loader, etc). See the declaration forSDWebImageContext for detailed information.

New Feature

Animated Image View

In 5.0, we introduced a brand new mechanism for supporting animated images. This includes animated image loading, rendering, decoding, and also supports customizations (for advanced users).

This animated image solution is available foriOS/tvOS/macOS. TheSDAnimatedImage is subclass ofUIImage/NSImage, andSDAnimatedImageView is subclass ofUIImageView/NSImageView, to make them compatible with the common frameworks APIs. SeeAnimated Image for more detailed information.

Image Transformer

In 5.0, we introduced an easy way to hook an image transformation process after the image was downloaded from network. This allows the user to easily scale, rotate, add rounded corner the original image and even chain a list of transformations. These transformed images will also be stored to the cache as they are after transformation. The reasons for this decision are: avoiding redoing the transformations (which can lead to unwanted behavior) and also time saving. SeeImage Transformer for more detailed information.

Customization

In 5.0, we refactored our framework architecture in many aspects. This makes our framework easier to customize for advanced users, without the need for hooking anything or forking. We introducedCustom Cache to control detailed cache loading behavior, and separate the memory cache & disk cache implementation. We introducedCustom Loader to allow custom loading from your own source (doesn't have to be the network). And also, we changed the currentCustom Coder to work better for custom image decoder/encoder and animated images.

View Indicator

In 5.0, we refactored the image loading indicator API into a better and extensible API foriOS/tvOS/macOS. This is suitable for easy usage like providing a loading view during the image loading process. SeeView Indicator for more detailed information.

FLAnimatedImage support moved to a dedicated plugin repo

In order to clean up things and make our core project do less things, we decided that theFLAnimatedImage integration does not belong here. From 5.0, this will still be available, but under a dedicated repoSDWebImageFLPlugin.

Photos Plugin

By taking the advantage of theCustom Loader feature, we introduced a plugin to allow easy loading images from the Photos Library. SeeSDWebImagePhotosPlugin for more detailed information.

Notable Behavior Changes (without API breaking)

Cache

Cache Paths

SDImageCache in 5.x, use~/Library/Caches/com.hackemist.SDImageCache/default/ as default cache path. However, 4.x use~/Library/Caches/default/com.hackemist.SDWebImageCache.default/. And don't be worried, we will do the migration automatically once the shared cache initialized.

However, if you have some other custom namespace cache instance, you should try to do migration by yourself. But typically, since the cache is designed to be invalid at any time, you'd better not to bind some important logic related on that cache path changes.

And, if you're previously using any version from5.0.0-beta to5.0.0-beta3, please note that the cache folder has been temporarily moved to~/Library/Caches/default/com.hackemist.SDImageCache.default/, however, the final release version of 5.0.0 use the path above. If you upgrade from those beta version, you may need manually do migration, check+[SDDiskCache moveCacheDirectoryFromPath:toPath:] for detail information.

Cache Cost Function

SDImageCacheConfig.maxMemoryCost can be used to specify the memory cost limit. In the 4.x, the cost function is thepixel count of images. However, 5.x change it into the totalbytes size of images.

Because for memory cache, we actually care about the memory usage about bytes, but not the count of pixels. And pixel count can not accurately represent the memory usage.

The bytes of a image occupied in the memory, can use the simple formula below:

bytes size =pixel count *bytes per pixel

Thebytes per pixel is a constant depends onimage pixel format. For mostly used images (8 bits per channel with alpha), the value is 4. So you can simply migrate your previous pixel count value with 4 multiplied.

Prefetcher

SDWebImagePrefetcher in 5.x, change the concept of fetching batch of URLs. Now, each time you callprefetchURLs:, you will get a token which represents the specified URLs list. It does not cancel the previous URLs which is prefetching, which make the shared prefetcher behaves more intuitively.

However, in 4.x, each time you callprefetchURLs:, it will cancel all previous URLs which is been prefetching.

If you still want the same behavior, manually callcancelPrefetching each time before anyprefetchURLs: calls.

  • Objective-C
SDWebImagePrefetcher *prefetcher = SDWebImagePrefetcher.sharedImagePrefetcher;[prefetchercancelPrefetching];[prefetcherprefetchURLs:@[url1, url2]];
  • Swift
letprefetcher=SDWebImagePrefetcher.sharedprefetcher.cancelPrefetching()prefetcher.prefetchURLs([url1, url2])

Error codes and domain

For image loading from network, if you don't passSDWebImageRetryFailed option, we'll try to blocking some URLs which is indeed mark as failed.

This check is done previously in a hard-coded logic for specify error codes. However, due to some compatible issue, we don't check the error domain. (Learn aboutNSError's domain and codes) And arbitrarily block some codes which may from custom download operation implementations.

Since in 5.x, we supports custom loaders which can use any third-party SDKs, and have their own error domain and error codes. So we now only filter the error codes inNSURLErrorDomain. If you have already using some error codes without error domain check, or you useCustom Download Operation, be sure to update it with the right way.

At the same time, our framework errors, now using the formalSDWebImageErrorDomain with the pre-defined codes. CheckSDWebImageError.h for details.

API Changes

SDImageCache

  • movedmaxMemoryCost andmaxMemoryCountLimit toSDImageCacheConfig
  • makeDiskCachePath: removed, useNSSearchPathForDirectoriesInDomains with NSString's Path API instead.
  • addReadOnlyCachePath: removed, useadditionalCachePathBlock instead
  • cachePathForKey:inPath: removed, usecachePathForKey: with NSString's path API instead.
  • defaultCachePathForKey: removed, usecachePathForKey: instead
  • SDCacheQueryCompletedBlock renamed toSDImageCacheQueryCompletionBlock
  • SDWebImageCheckCacheCompletionBlock renamed toSDImageCacheCheckCompletionBlock
  • SDWebImageCalculateSizeBlock renamed toSDImageCacheCalculateSizeBlock
  • getSize renamed tototalDiskSize
  • getDiskCount renamed tototalDiskCount

SDImageCacheConfig

  • shouldDecompressImages removed. UseSDImageCacheAvoidDecodeImage in cache options instead
  • maxCacheAge renamed tomaxDiskAge
  • maxCacheSize renamed tomaxDiskSize

SDWebImageManager

  • loadImageWithURL:options:progress:completed: changed thecompleted param requirement fromnullable tononnull
  • loadImageWithURL:options:progress:completed: return typeid<SDWebImageOperation> changed toSDWebImageCombinedOperation *
  • imageCache changed from nullable to nonnull. And property type changed fromSDImageCache * toid<SDImageCache>. The default value does not change.
  • imageDownloader renamed toimageLoader and changed from nullable to nonnull. And property type changed fromSDWebImageDownloader * toid<SDImageLoader>. The default value does not change.
  • cacheKeyFilter property type changed toid<SDWebImageCacheKeyFilter>, you can use+[SDWebImageCacheKeyFilter cacheKeyFilterWithBlock:] to create
  • cacheSerializer property type changed toid<SDWebImageCacheSerializer>, you can use+[SDWebImageCacheSerializer cacheSerializerWithBlock:] to create
  • SDWebImageCacheKeyFilterBlock'surl arg change from nullable to nonnull
  • initWithCache:downloader: 'scache arg type changed fromSDImageCache * toid<SDImageCache>
  • initWithCache:downloader renamed toinitWithCache:loader:
  • saveImageToCache:forURL: removed. UseSDImageCache storeImage:imageData:forKey:cacheType:completion: (orSDImageCache storeImage:forKey:toDisk:completion: if you use default cache class) withcacheKeyForURL: instead.
  • diskImageExistsForURL:completion: removed. UseSDImageCache containsImageForKey:cacheType:completion: (orSDImageCache diskImageExistsWithKey:completion: if you use default cache class) withcacheKeyForURL: instead.
  • cachedImageExistsForURL:completion removed. UseSDImageCache containsImageForKey:cacheType:completion: (orSDImageCache diskImageExistsWithKey:completion: andSDImageCache imageFromMemoryCacheForKey: if you use default cache class) withcacheKeyForURL: instead.

SDWebImageManagerDelegate

  • removedimageManager:transformDownloadedImage:forKey:, useSDImageTransformer with context option instead

UIView and subclasses (UIImageView, UIButton, ...)

  • sd_internalSetImageWithURL:placeholderImage:options:operationKey:setImageBlock:progress:completed: renamed toUIView sd_internalSetImageWithURL:placeholderImage:options:context:setImageBlock:progress:completed: (The biggest changes is that the completion block type fromSDExternalCompletionBlock toSDInternalCompletionBlock. Which allow advanced user to get more information of image loading process)
  • sd_internalSetImageWithURL:placeholderImage:options:operationKey:setImageBlock:progress:completed:context: removed
  • activity indicator refactoring - usesd_imageIndicator withSDWebImageActivityIndicator
    • sd_setShowActivityIndicatorView: removed
    • sd_setIndicatorStyle: removed
    • sd_showActivityIndicatorView removed
    • sd_addActivityIndicator: removed
    • sd_removeActivityIndicator: removed

UIImage

  • RenamedisGIF tosd_isAnimated, alsoNSImage isGIF renamed toNSImage sd_isAnimated
  • RenameddecodedImageWithImage: tosd_decodedImageWithImage:
  • RenameddecodedAndScaledDownImageWithImage: tosd_decodedAndScaledDownImageWithImage:
  • Renamedsd_animatedGIFWithData tosd_imageWithGIFData:
  • Removedsd_webpLoopCount

UIImageView

  • Removedsd_setImageWithPreviousCachedImageWithURL:placeholderImage:options:progress:completed
  • Removedsd_setAnimationImagesWithURLs:. You can useSDWebImagePrefetcher with memory cache to grab the batch loaded images
  • Removedsd_cancelCurrentAnimationImagesLoad. You can useSDWebImagePrefetcher with token cancel the batch loading images

SDWebImageDownloader

  • shouldDecompressImages moved toSDWebImageDownloaderConfig.shouldDecompressImages
  • maxConcurrentDownloads moved toSDWebImageDownloaderConfig.maxConcurrentDownloads
  • downloadTimeout moved toSDWebImageDownloaderConfig.downloadTimeout
  • operationClass moved toSDWebImageDownloaderConfig.operationClass
  • executionOrder moved toSDWebImageDownloaderConfig.executionOrder
  • urlCredential moved toSDWebImageDownloaderConfig.urlCredential
  • username moved toSDWebImageDownloaderConfig.username
  • password moved toSDWebImageDownloaderConfig.password
  • initWithSessionConfiguration: removed, useinitWithConfig: with session configuration instead
  • createNewSessionWithConfiguration: removed, useinitWithConfig: with new session configuration instead. To modify shared downloader configuration, provide customSDWebImageDownloaderConfig.defaultDownloaderConfig before it created.
  • headersFilter removed, userequestModifier instead
  • cancel: removed, use-[SDWebImageDownloadToken cancel] instead
  • shouldDecompressImages removed. UseSDWebImageDownloaderAvoidDecodeImage in downloader options instead
  • useSDImageLoaderProgressBlock instead ofSDWebImageDownloaderProgressBlock
  • useSDImageLoaderCompletedBlock instead ofSDWebImageDownloaderCompletedBlock

SDWebImageDownloaderOperation

  • initWithRequest:inSession:options:context: is now the designated initializer
  • RemovedshouldUseCredentialStorage property
  • SDWebImageDownloadOperationInterface protocol renamed toSDWebImageDownloadOperation
  • expectedSize removed, useresponse.expectedContentLength instead
  • shouldDecompressImages removed. UseSDWebImageDownloaderAvoidDecodeImage in downloader options instead.
  • response property change to readonly

SDWebImagePrefetcher

  • prefetchURLs: andprefetchURLs:progress:completed: return types changed fromvoid toSDWebImagePrefetchToken
  • prefetcherQueue property renamed todelegateQueue
  • maxConcurrentDownloads replaced withmaxConcurrentPrefetchCount

SDImageCoder

  • SDCGColorSpaceGetDeviceRGB() moved to+[SDImageCoderHelper colorSpaceGetDeviceRGB]
  • SDCGImageRefContainsAlpha(), moved to+[SDImageCoderHelper imageRefContainsAlpha:]
  • decodedImageWithData: replaced withdecodedImageWithData:options:
  • encodedDataWithImage:format: replaced withencodedDataWithImage:format:options
  • init method fromSDWebImageProgressiveCoder changed toinitIncrementalWithOptions:
  • incrementalDecodedImageWithData:finished replaced withupdateIncrementalData:finished andincrementalDecodedImageWithOptions: two APIs
  • removeddecompressedImage:data:options, use+[SDImageCoderHelper decodedImageWithImage:] and+[SDImageCoderHelper decodedAndScaledDownImageWithImage:limitBytes:] instead

SDWebImageOptions

  • SDWebImageProgressiveDownload renamed toSDWebImageProgressiveLoad
  • SDWebImageCacheMemoryOnly removed, use@{SDWebImageContextStoreCacheType : @(SDImageCacheTypeMemory)} context option instead. For Swift user, using[.storeCacheType: SDImageCacheType.memory.rawValue] (rawValue is important, same for other scalar type context option).
  • SDWebImageQueryDiskSync removed. UseSDWebImageQueryDiskDataSync instead.
  • SDWebImageQueryDataWhenInMemory removed. UseSDWebImageQueryMemoryData instead. If you want to query memory data sync as well, combined withSDWebImageQueryMemoryDataSync

Constants

  • SDWebImageInternalSetImageGroupKey removed
  • SDWebImageExternalCustomManagerKey renamed toSDWebImageContextCustomManager

Swift Specific API Change

In SDWebImage 5.0 we did a clean up of the API. We are using many modern Objective-C declarations to generate the Swift API. We now provide full nullability support, string enum, class property, and even custom Swift API name, all to make the framework easier to use for our Swift users. Here are the API change specify for Swift.

UIView+WebCache
  • sd_imageURL() changed tosd_imageURL
SDImageCache
  • shared() changed toshared
SDWebImageManager
  • shared() changed toshared
  • isRunning() changed toisRunning
SDWebImageDownloader
  • shared() changed toshared
  • setOperationClass(_:) available for Swift user withoperationClass property
  • setSuspended(_:) changed toisSuspended property
SDWebImageDownloadOperation
  • SDWebImageDownloadOperationInterface protocol renamed toSDWebImageDownloadOperationProtocol.
SDImageCodersManager
  • sharedInstance() changed toshared
SDImageIOCoder
  • shared() changed toshared
SDImageGIFCoder
  • shared() changed toshared
SDImageWebPCoder
  • shared() changed toshared
NSData-ImageContentType
  • sd_UTTypeFromSDImageFormat returnCFString instead ofUnmanaged<CFString>
UIButton-WebCache
  • sd_currentImageURL() changed tosd_currentImageURL
NSButton-WebCache
  • sd_currentImageURL() changed tosd_currentImageURL
  • sd_currentAlternateImageURL() changed tosd_currentAlternateImageURL

Full API Diff

For advanced user who need the detailed API diff, we provide the full diff in a HTML web page (based on 4.4.6 and 5.0.0):

SDWebImage 5.0 API Diff.

Clone this wiki locally


[8]ページ先頭

©2009-2025 Movatter.jp