AlamofireImage:Alamofire的图像组件库
阿拉莫火图片
AlamofireImage 是 Alamofire 的图像组件库。
特征
- [x] 图像响应序列化程序
- [x] 用于膨胀/缩放/舍入/核心映像的UIImage扩展
- [x] 单通道和多通道图像滤光片
- [x] 自动清除内存中映像缓存
- [x] 优先队列顺序图像下载
- [x] 使用 URL 身份验证
- [x] UIImageView 异步远程下载与占位符
- [x] UIImageView 筛选器和转换
- [x] 全面的测试覆盖率
- [x] 完整文档
要求
- iOS 10.0+ / macOS 10.12+ / tvOS 10.0+ / watchOS 3.0+
- Xcode 11+
- 斯威夫特 5.1+
迁移指南
依赖
Communication
- If you need to find or understand an API, check our documentation.
- If you need help with an AlamofireImage feature, use our forum on swift.org.
- If you'd like to discuss AlamofireImage best practices, use our forum on swift.org.
- If you'd like to discuss a feature request, use our forum on swift.org.
- If you found a bug, open an issue and follow the guide. The more detail the better!
- If you want to contribute, submit a pull request.
Installation
CocoaPods
CocoaPods is a dependency manager for Cocoa projects. For usage and installation instructions, visit their website. To integrate AlamofireImage into your Xcode project using CocoaPods, specify it in your :Podfile
Carthage
Carthage is a decentralized dependency manager that builds your dependencies and provides you with binary frameworks. To integrate AlamofireImage into your Xcode project using Carthage, specify it in your :Cartfile
Swift Package Manager
The Swift Package Manager is a tool for automating the distribution of Swift code and is integrated into the compiler. It is in early development, but AlamofireImage does support its use on supported platforms.swift
Once you have your Swift package set up, adding AlamofireImage as a dependency is as easy as adding it to the value of your .dependencies
Package.swift
Manually
If you prefer not to use either of the aforementioned dependency managers, you can integrate AlamofireImage into your project manually.
Embedded Framework
- Open up Terminal, into your top-level project directory, and run the following command "if" your project is not initialized as a git repository:
cd
- Add AlamofireImage as a git submodule by running the following command:
-
Open the new folder, and drag the into the Project Navigator of your application's Xcode project.
AlamofireImage
AlamofireImage.xcodeproj
It should appear nested underneath your application's blue project icon. Whether it is above or below all the other Xcode groups does not matter.
-
Select the in the Project Navigator and verify the deployment target matches that of your application target.
AlamofireImage.xcodeproj
-
Next, select your application project in the Project Navigator (blue project icon) to navigate to the target configuration window and select the application target under the "Targets" heading in the sidebar.
-
In the tab bar at the top of that window, open the "General" panel.
-
Click on the button under the "Embedded Binaries" section.
+
-
You will see two different folders each with two different versions of the nested inside a folder.
AlamofireImage.xcodeproj
AlamofireImage.framework
Products
It does not matter which folder you choose from, but it does matter whether you choose the top or bottom .
Products
AlamofireImage.framework
-
Select the top for iOS and the bottom one for OS X.
AlamofireImage.framework
You can verify which one you selected by inspecting the build log for your project. The build target for will be listed as either , , or .
AlamofireImage
AlamofireImage iOS
AlamofireImage macOS
AlamofireImage tvOS
AlamofireImage watchOS
-
And that's it!
The is automagically added as a target dependency, linked framework and embedded framework in a copy files build phase which is all you need to build on the simulator and a device.
AlamofireImage.framework
Usage
Image Response Serializers
The AlamofireImage response image serializers support a wide range of image types including:
image/png
image/jpeg
image/tiff
image/gif
image/ico
image/x-icon
image/bmp
image/x-bmp
image/x-xbitmap
image/x-ms-bmp
image/x-win-bitmap
image/heic
application/octet-stream
(added for iOS 13 support)
If the image you are attempting to download is an invalid MIME type not in the list, you can add custom acceptable content types using the extension on the type.
addAcceptableImageContentTypes
DataRequest
UIImage Extensions
There are several extensions designed to make the common image manipulation operations as simple as possible.UIImage
Inflation
Inflating compressed image formats (such as PNG or JPEG) in a background queue can significantly improve drawing performance on the main thread.
Scaling
Rounded Corners
Core Image Filters
Image Filters
The protocol was designed to make it easy to apply a filter operation and cache the result after an image finished downloading. It defines two properties to facilitate this functionality.ImageFilter
The closure contains the operation used to create a modified version of the specified image. The property is a string used to uniquely identify the filter operation. This is useful when adding filtered versions of an image to a cache. All identifier properties inside AlamofireImage are implemented using protocol extensions.filter
identifier
Single Pass
The single pass image filters only perform a single operation on the specified image.
The current list of single pass image filters includes:
ScaledToSizeFilter
- Scales an image to a specified size.AspectScaledToFitSizeFilter
- Scales an image from the center while maintaining the aspect ratio to fit within a specified size.AspectScaledToFillSizeFilter
- Scales an image from the center while maintaining the aspect ratio to fill a specified size. Any pixels that fall outside the specified size are clipped.RoundedCornersFilter
- Rounds the corners of an image to the specified radius.CircleFilter
- Rounds the corners of an image into a circle.BlurFilter
- Blurs an image using a filter with the specified blur radius.CIGaussianBlur
Each image filter is built ontop of the extensions.
UIImage
Multi-Pass
The multi-pass image filters perform multiple operations on the specified image.
The current list of multi-pass image filters includes:
ScaledToSizeWithRoundedCornersFilter
- Scales an image to a specified size, then rounds the corners to the specified radius.AspectScaledToFillSizeWithRoundedCornersFilter
- Scales an image from the center while maintaining the aspect ratio to fit within a specified size, then rounds the corners to the specified radius.ScaledToSizeCircleFilter
- Scales an image to a specified size, then rounds the corners into a circle.AspectScaledToFillSizeCircleFilter
- Scales an image from the center while maintaining the aspect ratio to fit within a specified size, then rounds the corners into a circle.
Image Cache
Image caching can become complicated when it comes to network images. is quite powerful and does a great job reasoning through the various cache policies and headers. However, it is not equipped to handle caching multiple modified versions of those images.URLCache
Cache-Control
For example, let's say you need to download an album of images. Your app needs to display both the thumbnail version as well as the full size version at various times. Due to performance issues, you want to scale down the thumbnails to a reasonable size before rendering them on-screen. You also need to apply a global CoreImage filter to the full size images when displayed. While can easily handle storing the original downloaded image, it cannot store these different variants. What you really need is another caching layer designed to handle these different variants.URLCache
The in AlamofireImage fills the role of that additional caching layer. It is an in-memory image cache used to store images up to a given memory capacity. When the memory capacity is reached, the image cache is sorted by last access date, then the oldest image is continuously purged until the preferred memory usage after purge is met. Each time an image is accessed through the cache, the internal access date of the image is updated.AutoPurgingImageCache
Add / Remove / Fetch Images
Interacting with the protocol APIs is very straightforward.ImageCache
URL Requests
The protocol extends the protocol by adding support for caching. This allows a and an additional identifier to generate the unique identifier for the image in the cache.ImageRequestCache
ImageCache
URLRequest
URLRequest
Auto-Purging
Each time an image is fetched from the cache, the cache internally updates the last access date for that image.
By updating the last access date for each image, the image cache can make more informed decisions about which images to purge when the memory capacity is reached. The automatically evicts images from the cache in order from oldest last access date to newest until the memory capacity drops below the .AutoPurgingImageCache
preferredMemoryCapacityAfterPurge
It is important to set reasonable default values for the and when you are initializing your image cache. By default, the equals 100 MB and the equals 60 MB.
memoryCapacity
preferredMemoryCapacityAfterPurge
memoryCapacity
preferredMemoryCapacityAfterPurge
Memory Warnings
The also listens for memory warnings from your application and will purge all images from the cache if a memory warning is observed.AutoPurgingImageCache
Image Downloader
The class is responsible for downloading images in parallel on a prioritized queue. It uses an internal Alamofire instance to handle all the downloading and response image serialization. By default, the initialization of an uses a default with the most common parameter values.ImageDownloader
SessionManager
ImageDownloader
URLSessionConfiguration
If you need to customize the type or parameters, then simply provide your own rather than using the default.
URLSessionConfiguration
Downloading an Image
Make sure to keep a strong reference to the instance, otherwise the closure will not be called because the reference will go out of scope before the closure can be called.
ImageDownloader
completion
downloader
completion
Applying an ImageFilter
Authentication
If your images are behind HTTP Basic Auth, you can append the or the to the instance. The credentials will be applied to all future download requests.user:password:
credential
ImageDownloader
Download Prioritization
The maintains an internal queue of pending download requests. Depending on your situation, you may want incoming downloads to be inserted at the front or the back of the queue. The enumeration allows you to specify which behavior you would prefer.ImageDownloader
DownloadPrioritization
The is initialized with a queue by default.
ImageDownloader
.fifo
Image Caching
The uses a combination of an and to create a very robust, high performance image caching system.ImageDownloader
URLCache
AutoPurgingImageCache
URLCache
The is used to cache all the original image content downloaded from the server. By default, it is initialized with a memory capacity of 20 MB and a disk capacity of 150 MB. This allows up to 150 MB of original image data to be stored on disk at any given time. While these defaults have been carefully set, it is very important to consider your application's needs and performance requirements and whether these values are right for you.URLCache
If you wish to disable this caching layer, create a custom with the property set to and use that configuration when initializing the .
URLSessionConfiguration
urlCache
nil
ImageDownloader
Image Cache
The is used to cache all the potentially filtered image content after it has been downloaded from the server. This allows multiple variants of the same image to also be cached, rather than having to re-apply the image filters to the original image each time it is required. By default, an is initialized with a memory capacity of 100 MB and a preferred memory usage after purge limit of 60 MB. This allows up to 100 MB of most recently accessed filtered image content to be stored in-memory at a given time.ImageCache
AutoPurgingImageCache
Setting Ideal Capacity Limits
Determining the ideal the in-memory and on-disk capacity limits of the and requires a bit of forethought. You must carefully consider your application's needs, and tailor the limits accordingly. By default, the combination of caches offers the following storage capacities:URLCache
AutoPurgingImageCache
- 150 MB of on-disk storage (original image only)
- 20 MB of in-memory original image data storage (original image only)
- 100 MB of in-memory storage of filtered image content (filtered image if using filters, otherwise original image)
- 60 MB preferred memory capacity after purge of filtered image content
If you do not use image filters, it is advised to set the memory capacity of the to zero. Otherwise, you will be storing the original image data in both the URLCache's in-memory store as well as the AlamofireImage in-memory store.
URLCache
Duplicate Downloads
Sometimes application logic can end up attempting to download an image more than once before the initial download request is complete. Most often, this results in the image being downloaded more than once. AlamofireImage handles this case elegantly by merging the duplicate downloads. The image will only be downloaded once, yet both completion handlers will be called.
Image Filter Reuse
In addition to merging duplicate downloads, AlamofireImage can also merge duplicate image filters. If two image filters with the same identifier are attached to the same download, the image filter is only executed once and both completion handlers are called with the same resulting image. This can save large amounts of time and resources for computationally expensive filters such as ones leveraging CoreImage.
Request Receipts
Sometimes it is necessary to cancel an image download for various reasons. AlamofireImage can intelligently handle cancellation logic in the by leveraging the type along with the method. Each download request vends a which can be later used to cancel the request.ImageDownloader
RequestReceipt
cancelRequestForRequestReceipt
RequestReceipt
By cancelling the request through the using the , AlamofireImage is able to determine how to best handle the cancellation. The cancelled download will always receive a cancellation error, while duplicate downloads are allowed to complete. If the download is already active, it is allowed to complete even though the completion handler will be called with a cancellation error. This greatly improves performance of table and collection views displaying large amounts of images.ImageDownloader
RequestReceipt
It is NOT recommended to directly call on the in the . Doing so can lead to issues such as duplicate downloads never being allowed to complete.
cancel
request
RequestReceipt
UIImageView Extension
The UIImage Extensions, Image Filters, Image Cache and Image Downloader were all designed to be flexible and standalone, yet also to provide the foundation of the extension. Due to the powerful support of these classes, protocols and extensions, the APIs are concise, easy to use and contain a large amount of functionality.UIImageView
UIImageView
Setting Image with URL
Setting the image with a URL will asynchronously download the image and set it once the request is finished.
If the image is cached locally, the image is set immediately.
Placeholder Images
By specifying a placeholder image, the image view uses the placeholder image until the remote image is downloaded.
If the remote image is cached locally, the placeholder image is never set.
Image Filters
If an image filter is specified, it is applied asynchronously after the remote image is downloaded. Once the filter execution is complete, the resulting image is set on the image view.
If the remote image with the applied filter is cached locally, the image is set immediately.
Image Transitions
By default, there is no image transition animation when setting the image on the image view. If you wish to add a cross dissolve or flip-from-bottom animation, then specify an with the preferred duration.ImageTransition
If the remote image is cached locally, the image transition is ignored.
Image Downloader
The extension is powered by the default instance. To customize cache capacities, download priorities, request cache policies, timeout durations, etc., please refer to the Image Downloader documentation.UIImageView
ImageDownloader
Authentication
If an image requires and authentication credential from the extension, it can be provided as follows:UIImageView
Credits
Alamofire is owned and maintained by the Alamofire Software Foundation. You can follow them on Twitter at @AlamofireSF for project updates and releases.
Security Disclosure
If you believe you have identified a security vulnerability with AlamofireImage, you should report it as soon as possible via email to security@alamofire.org. Please do not post it to a public issue tracker.
Donations
The ASF is looking to raise money to officially stay registered as a federal non-profit organization.
Registering will allow us members to gain some legal protections and also allow us to put donations to use, tax free.
Donating to the ASF will enable us to:
- Pay our yearly legal fees to keep the non-profit in good status
- Pay for our mail servers to help us stay on top of all questions and security issues
- Potentially fund test servers to make it easier for us to test the edge cases
- Potentially fund developers to work on one of our projects full-time
The community adoption of the ASF libraries has been amazing.
We are greatly humbled by your enthusiasm around the projects, and want to continue to do everything we can to move the needle forward.
With your continued support, the ASF will be able to improve its reach and also provide better legal safety for the core members.
If you use any of our libraries for work, see if your employers would be interested in donating.
Any amount you can donate today to help us reach our goal would be greatly appreciated.
License
AlamofireImage is released under the MIT license. See LICENSE for details.