SDWebImageSwiftUI

SDWebImageSwiftUI

基于SDWebImage的SwiftUI图像加载框架 支持异步缓存与动画

SDWebImageSwiftUI是基于SDWebImage的SwiftUI图像加载框架。该框架提供异步图像加载、内存/磁盘缓存和动画图像播放功能。它包含WebImage和AnimatedImage等符合SwiftUI设计的API,支持占位图、加载选项、进度指示和过渡动画。SDWebImageSwiftUI针对SwiftUI进行了优化,适用于iOS 14+、macOS 11+等平台,为SwiftUI应用提供完整的图像处理方案。

SDWebImageSwiftUISwiftUI图片加载动画图片缓存Github开源项目

SDWebImageSwiftUI

CI Status Version License Platform Carthage compatible SwiftPM compatible codecov

If you support iOS 15+/macOS 12+ only and don't care about animated image format, try SwiftUI's AsyncImage

What's for

SDWebImageSwiftUI is a SwiftUI image loading framework, which based on SDWebImage.

It brings all your favorite features from SDWebImage, like async image loading, memory/disk caching, animated image playback and performances.

The framework provide the different View structs, which API match the SwiftUI framework guideline. If you're familiar with Image, you'll find it easy to use WebImage and AnimatedImage.

Apple VisionOS

From v3.0.0, SDWebImageSwiftUI can be compiled for visionOS platform. However, due to the lacking package manager support (need tools update), we don't support CocoaPods/SPM yet.

You can only use the Xcode's built-in package manager dependency to build on visionOS.

To run the visionOS example, you need to clone and add both SDWebImage and SDWebImageSwiftUI, open the SDWebImageSwiftUI.xcworkspace and drag those folders to become local package dependency, see: Editing a package dependency as a local package

If you really want to build framework instead of using Xcode's package dependency, following the manual steps below:

  1. Clone SDWebImage, open SDWebImage.xcodeproj and build SDWebImage target for visionOS platform (Change MACH_O_TYPE to static library if you need)
  2. Clone SDWebImageSwiftUI, create directory at Carthage/Build/visionOS and copy SDWebImage.framework into it
  3. Open SDWebImageSwiftUI.xcodeproj and build SDWebImageSwiftUI visionOS target

Features

Since SDWebImageSwiftUI is built on top of SDWebImage, it provide both the out-of-box features as well as advanced powerful features you may want in real world Apps. Check our Wiki when you need:

  • Animated Image full-stack solution, with balance of CPU && RAM
  • Progressive image loading, with animation support
  • Reusable download, never request single URL twice
  • URL Request / Response Modifier, provide custom HTTP Header
  • Image Transformer, apply corner radius or CIFilter
  • Multiple caches system, query from different source
  • Multiple loaders system, load from different resource

You can also get all benefits from the existing community around with SDWebImage. You can have massive image format support (GIF/APNG/WebP/HEIF/AVIF/SVG/PDF) via Coder Plugins, PhotoKit support via SDWebImagePhotosPlugin, Firebase integration via FirebaseUI, etc.

Besides all these features, we do optimization for SwiftUI, like Binding, View Modifier, using the same design pattern to become a good SwiftUI citizen.

Version

This framework is under heavily development, it's recommended to use the latest release as much as possible (including SDWebImage dependency).

This framework follows Semantic Versioning. Each source-break API changes will bump to a major version.

Changelog

This project use keep a changelog format to record the changes. Check the CHANGELOG.md about the changes between versions. The changes will also be updated in Release page.

Contribution

All issue reports, feature requests, contributions, and GitHub stars are welcomed. Hope for active feedback and promotion if you find this framework useful.

Requirements

  • Xcode 14+
  • iOS 14+
  • macOS 11+
  • tvOS 14+
  • watchOS 7+
  • visionOS 1+

for SwiftUI 1.0 (iOS 13)

iOS 14(macOS 11) introduce the SwiftUI 2.0, which keep the most API compatible, but changes many internal behaviors, which breaks the SDWebImageSwiftUI's function.

From v3.0.0, SDWebImageSwiftUI drop iOS 13 support. To use on iOS 13, checkout the latest v2.x version (or using 2.x branch) instead.

for future transition

Since SDWebImage 6.0 will introduce mixed Swift/Objc codebase, this repo will migrate into SDWebImage Core Repo.

But don't worry, we will use the automatic cross module overlay, whic means, you can use:

import SwiftUI import SDWebImage

to works like:

import SwiftUI
import SDWebImage
import SDWebImageSwiftUI // <-- Automatic infer this

You will automatically link the SDWebImageSwiftUI, and this library's naming will still be preserved in SPM target. So the transition is smooth for most of you, I don't want to bump another major version. The 3.x is the final version for SDWebImageSwiftUI dedicated repo

Note: For super advanced user, if you using some custom Swift toolchain, be sure to pass -Xfrontend -enable-cross-import-overlays

Installation

Swift Package Manager

SDWebImageSwiftUI is available through Swift Package Manager.

  • For App integration

For App integration, you should using Xcode 12 or higher, to add this package to your App target. To do this, check Adding Package Dependencies to Your App about the step by step tutorial using Xcode.

  • For downstream framework

For downstream framework author, you should create a Package.swift file into your git repo, then add the following line to mark your framework dependent our SDWebImageSwiftUI.

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

CocoaPods

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

pod 'SDWebImageSwiftUI'

Carthage

SDWebImageSwiftUI is available through Carthage.

github "SDWebImage/SDWebImageSwiftUI"

Usage

Using WebImage to load network image

  • Supports placeholder and detail options control for image loading as SDWebImage
  • Supports progressive image loading (like baseline)
  • Supports success/failure/progress changes event for custom handling
  • Supports indicator with activity/progress indicator and customization
  • Supports built-in animation and transition, powered by SwiftUI
  • Supports animated image as well!
var body: some View { WebImage(url: URL(string: "https://nokiatech.github.io/heif/content/images/ski_jump_1440x960.heic")) { image in image.resizable() // Control layout like SwiftUI.AsyncImage, you must use this modifier or the view will use the image bitmap size } placeholder: { Rectangle().foregroundColor(.gray) } // Supports options and context, like `.delayPlaceholder` to show placeholder only when error .onSuccess { image, data, cacheType in // Success // Note: Data exist only when queried from disk cache or network. Use `.queryMemoryData` if you really need data } .indicator(.activity) // Activity Indicator .transition(.fade(duration: 0.5)) // Fade Transition with duration .scaledToFit() .frame(width: 300, height: 300, alignment: .center) }

Note: This WebImage using Image for internal implementation, which is the best compatible for SwiftUI layout and animation system. But unlike SwiftUI's Image which does not support animated image or vector image, WebImage supports animated image as well (by defaults from v2.0.0).

However, The WebImage animation provide simple common use case, so it's still recommend to use AnimatedImage for advanced controls like progressive animation rendering, or vector image rendering.

@State var isAnimating: Bool = true var body: some View { WebImage(url: URL(string: "https://raw.githubusercontent.com/liyong03/YLGIFImage/master/YLGIFImageDemo/YLGIFImageDemo/joy.gif"), isAnimating: $isAnimating)) // Animation Control, supports dynamic changes // The initial value of binding should be true .customLoopCount(1) // Custom loop count .playbackRate(2.0) // Playback speed rate .playbackMode(.bounce) // Playback normally to the end, then reversely back to the start // `WebImage` supports advanced control just like `AnimatedImage`, but without the progressive animation support }

Note: For indicator, you can custom your own as well. For example, iOS 14/watchOS 7 introduce the new ProgressView, which can be easily used via:

WebImage(url: url) .indicator(.activity)

or you can just write like:

WebImage(url: url) .indicator { Indicator { _, _ in ProgressView() } }

Using AnimatedImage to play animation

  • Supports network image as well as local data and bundle image
  • Supports animated image format as well as vector image format
  • Supports animated progressive image loading (like web browser)
  • Supports animation control using the SwiftUI Binding
  • Supports indicator and transition, powered by SDWebImage and Core Animation
  • Supports advanced control like loop count, playback rate, buffer size, runloop mode, etc
  • Supports coordinate with native UIKit/AppKit view
var body: some View { Group { AnimatedImage(url: URL(string: "https://raw.githubusercontent.com/liyong03/YLGIFImage/master/YLGIFImageDemo/YLGIFImageDemo/joy.gif"), placeholderImage: .init(systemName: "photo")) // Placeholder Image // Supports options and context, like `.progressiveLoad` for progressive animation loading .onFailure { error in // Error } .resizable() // Resizable like SwiftUI.Image, you must use this modifier or the view will use the image bitmap size .indicator(.activity) // Activity Indicator .transition(.fade) // Fade Transition .scaledToFit() // Attention to call it on AnimatedImage, but not `some View` after View Modifier (Swift Protocol Extension method is static dispatched) // Supports SwiftUI ViewBuilder placeholder as well AnimatedImage(url: url) { Circle().foregroundColor(.gray) } // Data AnimatedImage(data: try! Data(contentsOf: URL(fileURLWithPath: "/tmp/foo.webp"))) .customLoopCount(1) // Custom loop count .playbackRate(2.0) // Playback speed rate // Bundle (not Asset Catalog) AnimatedImage(name: "animation1.gif", isAnimating: $isAnimating) // Animation control binding .maxBufferSize(.max) .onViewUpdate { view, context in // Advanced native view coordinate // AppKit tooltip for mouse hover view.toolTip = "Mouseover Tip" // UIKit advanced content mode view.contentMode = .topLeft // Coordinator, used for Cocoa Binding or Delegate method let coordinator = context.coordinator } } }

Note: AnimatedImage supports both image url or image data for animated image format. Which use the SDWebImage's Animated ImageView for internal implementation. Pay attention that since this base on UIKit/AppKit representable, some advanced SwiftUI layout and animation system may not work as expected. You may need UIKit/AppKit and Core Animation to modify the native view.

Note: AnimatedImage some methods like .transition, .indicator and .aspectRatio have the same naming as SwiftUI.View protocol methods. But the args receive the different type. This is because AnimatedImage supports to be used with UIKit/AppKit component and animation. If you find ambiguity, use full type declaration instead of the dot expression syntax.

Note: some of methods on AnimatedImage will return some View, a new Modified Content. You'll lose the type related modifier method. For this case, you can either reorder the method call, or use native view (actually SDAnimatedImageView) in .onViewUpdate, use UIKIt/AppKit API for rescue.

// Using UIKit components var body: some View { AnimatedImage(name: "animation2.gif") .indicator(SDWebImageProgressIndicator.default) // UIKit indicator component .transition(SDWebImageTransition.flipFromLeft) // UIKit animation transition } // Using SwiftUI components var body: some View { AnimatedImage(name: "animation2.gif") .indicator(Indicator.progress) // SwiftUI indicator component .transition(AnyTransition.flipFromLeft) // SwiftUI animation transition }

Which View to choose

Why we have two different View types here, is because of current SwiftUI limit. But we're aimed to provide best solution for all use cases.

If you don't need animated image, prefer to use WebImage firstly. Which behaves the seamless as built-in SwiftUI View. If SwiftUI works, it works. If SwiftUI doesn't work, it either :)

If you need simple animated image, use WebImage. Which provide the basic animated image support. But it does not support progressive animation rendering, nor vector image, if you don't care about this.

If you need powerful animated image, AnimatedImage is the one to choose. Remember it supports static image as well, you don't need to check the format, just use as it. Also, some powerful feature like UIKit/AppKit tint color, vector image, symbol image configuration, tvOS layered image, only available in AnimatedImage but not currently in SwfitUI.

But, because AnimatedImage use UIViewRepresentable and driven by UIKit, currently there may be some small incompatible issues between UIKit and SwiftUI layout and animation system, or bugs related to SwiftUI itself. We try our best to match SwiftUI behavior, and provide the same API as WebImage, which make it easy to switch between these two types if needed.

Use ImageManager for your own View type

The ImageManager is a class which conforms to Combine's ObservableObject protocol. Which is the core fetching data source of WebImage we provided.

For advanced use case, like loading image into the complicated View graph which you don't want to use WebImage. You can directly bind your own View type with the Manager.

It looks familiar like SDWebImageManager, but it's built for SwiftUI world, which provide the Source of Truth for loading images. You'd better use SwiftUI's @ObservedObject to bind each single manager instance for your View instance, which automatically update your View's body when image status changed.

struct MyView : View { @ObservedObject var imageManager = ImageManager() var body: some View { // Your custom complicated view graph Group { if imageManager.image != nil { Image(uiImage: imageManager.image!) } else { Rectangle().fill(Color.gray) } } // Trigger image loading when appear .onAppear { self.imageManager.load(url: url) } // Cancel image loading when disappear .onDisappear { self.imageManager.cancel() } } }

Customization and configuration setup

This framework is based on SDWebImage, which supports advanced customization and configuration to meet different users' demand.

You can register multiple coder plugins for external image format. You can register multiple caches (different paths and config), multiple loaders (URLSession and Photos URLs). You can control the cache expiration date, size, download priority, etc. All in our wiki.

The best place to put these setup code

编辑推荐精选

博思AIPPT

博思AIPPT

AI一键生成PPT,就用博思AIPPT!

博思AIPPT,新一代的AI生成PPT平台,支持智能生成PPT、AI美化PPT、文本&链接生成PPT、导入Word/PDF/Markdown文档生成PPT等,内置海量精美PPT模板,涵盖商务、教育、科技等不同风格,同时针对每个页面提供多种版式,一键自适应切换,完美适配各种办公场景。

热门AI工具AI办公办公工具智能排版AI生成PPT博思AIPPT海量精品模板AI创作
潮际好麦

潮际好麦

AI赋能电商视觉革命,一站式智能商拍平台

潮际好麦深耕服装行业,是国内AI试衣效果最好的软件。使用先进AIGC能力为电商卖家批量提供优质的、低成本的商拍图。合作品牌有Shein、Lazada、安踏、百丽等65个国内外头部品牌,以及国内10万+淘宝、天猫、京东等主流平台的品牌商家,为卖家节省将近85%的出图成本,提升约3倍出图效率,让品牌能够快速上架。

iTerms

iTerms

企业专属的AI法律顾问

iTerms是法大大集团旗下法律子品牌,基于最先进的大语言模型(LLM)、专业的法律知识库和强大的智能体架构,帮助企业扫清合规障碍,筑牢风控防线,成为您企业专属的AI法律顾问。

SimilarWeb流量提升

SimilarWeb流量提升

稳定高效的流量提升解决方案,助力品牌曝光

稳定高效的流量提升解决方案,助力品牌曝光

Sora2视频免费生成

Sora2视频免费生成

最新版Sora2模型免费使用,一键生成无水印视频

最新版Sora2模型免费使用,一键生成无水印视频

Transly

Transly

实时语音翻译/同声传译工具

Transly是一个多场景的AI大语言模型驱动的同声传译、专业翻译助手,它拥有超精准的音频识别翻译能力,几乎零延迟的使用体验和支持多国语言可以让你带它走遍全球,无论你是留学生、商务人士、韩剧美剧爱好者,还是出国游玩、多国会议、跨国追星等等,都可以满足你所有需要同传的场景需求,线上线下通用,扫除语言障碍,让全世界的语言交流不再有国界。

讯飞绘文

讯飞绘文

选题、配图、成文,一站式创作,让内容运营更高效

讯飞绘文,一个AI集成平台,支持写作、选题、配图、排版和发布。高效生成适用于各类媒体的定制内容,加速品牌传播,提升内容营销效果。

AI助手热门AI工具AI创作AI辅助写作讯飞绘文内容运营个性化文章多平台分发
TRAE编程

TRAE编程

AI辅助编程,代码自动修复

Trae是一种自适应的集成开发环境(IDE),通过自动化和多元协作改变开发流程。利用Trae,团队能够更快速、精确地编写和部署代码,从而提高编程效率和项目交付速度。Trae具备上下文感知和代码自动完成功能,是提升开发效率的理想工具。

热门AI工具生产力协作转型TraeAI IDE
商汤小浣熊

商汤小浣熊

最强AI数据分析助手

小浣熊家族Raccoon,您的AI智能助手,致力于通过先进的人工智能技术,为用户提供高效、便捷的智能服务。无论是日常咨询还是专业问题解答,小浣熊都能以快速、准确的响应满足您的需求,让您的生活更加智能便捷。

imini AI

imini AI

像人一样思考的AI智能体

imini 是一款超级AI智能体,能根据人类指令,自主思考、自主完成、并且交付结果的AI智能体。

下拉加载更多