Giter VIP home page Giter VIP logo

sdwebimage's Introduction

Build Status Pod Version Pod Platform Pod License Carthage compatible SwiftPM compatible Mac Catalyst compatible codecov

This library provides an async image downloader with cache support. For convenience, we added categories for UI elements like UIImageView, UIButton, MKAnnotationView.

Note: SD is the prefix for Simple Design (which is the team name in Daily Motion company from the author Olivier Poitrey)

Features

For Apple visionOS

From 5.19+, SDWebImage supports visionOS on all Package Managers (include CocoaPods/Carthage/SPM). Upgrade the related tools if you're facing issues.

For 5.18+, SDWebImage can be compiled for visionOS platform. However, it's still in beta and may contains issues unlike the stable iOS UIKit support. Welcome to have a try and report issue.

To build on visionOS, currently we only support the standard Xcode integration.

See Installation with Swift Package Manager and Manual Installation Guide below.

Supported Image Formats

  • Image formats supported by Apple system (JPEG, PNG, TIFF, BMP, ...), including GIF/APNG animated image
  • HEIC format from iOS 11/macOS 10.13, including animated HEIC from iOS 13/macOS 10.15 via SDWebImageHEICCoder. For lower firmware, use coder plugin SDWebImageHEIFCoder
  • WebP format from iOS 14/macOS 11.0 via SDWebImageAWebPCoder. For lower firmware, use coder plugin SDWebImageWebPCoder
  • JPEG-XL format from iOS 17/macOS 14.0 built-in. For lower firmware, use coder plugin SDWebImageJPEGXLCoder
  • Support extendable coder plugins for new image formats like BPG, AVIF. And vector format like PDF, SVG. See all the list in Image coder plugin List

Additional modules and Ecosystem

In order to keep SDWebImage focused and limited to the core features, but also allow extensibility and custom behaviors, during the 5.0 refactoring we focused on modularizing the library. As such, we have moved/built new modules to SDWebImage org.

SwiftUI

SwiftUI is an innovative UI framework written in Swift to build user interfaces across all Apple platforms.

We support SwiftUI by building a brand new framework called SDWebImageSwiftUI, which is built on top of SDWebImage core functions (caching, loading and animation).

The new framework introduce two View structs WebImage and AnimatedImage for SwiftUI world, ImageIndicator modifier for any View, ImageManager observable object for data source. Supports iOS 13+/macOS 10.15+/tvOS 13+/watchOS 6+ and Swift 5.1. Have a nice try and provide feedback!

Coders for additional image formats

Custom Caches

Custom Loaders

  • SDWebImagePhotosPlugin - plugin to support loading images from Photos (using Photos.framework)
  • SDWebImageLinkPlugin - plugin to support loading images from rich link url, as well as LPLinkView (using LinkPresentation.framework)

Integration with 3rd party libraries

Community driven popular libraries

  • FirebaseUI - Firebase Storage binding for query images, based on SDWebImage loader system
  • react-native-fast-image - React Native fast image component, based on SDWebImage Animated Image solution
  • flutter_image_compress - Flutter compresses image plugin, based on SDWebImage WebP coder plugin

Make our lives easier

You can use those directly, or create similar components of your own, by using the customizable architecture of SDWebImage.

Requirements

  • iOS 9.0 or later
  • tvOS 9.0 or later
  • watchOS 2.0 or later
  • macOS 10.11 or later (10.15 for Catalyst)
  • visionOS 1.0 or later
  • Xcode 14.0 or later (visionOS requires Xcode 15.0)

Backwards compatibility

Getting Started

Who Uses It

Communication

  • If you need help, use Stack Overflow. (Tag 'sdwebimage')
  • If you'd like to ask a general question, use Stack Overflow.
  • If you found a bug, open an issue.
  • If you have a feature request, open an issue.
  • If you need IRC channel, use Gitter.

Contribution

How To Use

  • Objective-C
#import <SDWebImage/SDWebImage.h>
...
[imageView sd_setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
             placeholderImage:[UIImage imageNamed:@"placeholder.png"]];
  • Swift
import SDWebImage

imageView.sd_setImage(with: URL(string: "http://www.domain.com/path/to/image.jpg"), placeholderImage: UIImage(named: "placeholder.png"))

Animated Images (GIF) support

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 for iOS/tvOS/macOS. The SDAnimatedImage is subclass of UIImage/NSImage, and SDAnimatedImageView is subclass of UIImageView/NSImageView, to make them compatible with the common frameworks APIs.

The SDAnimatedImageView supports the familiar image loading category methods, works like drop-in replacement for UIImageView/NSImageView.

Don't have UIView (like WatchKit or CALayer)? you can still use SDAnimatedPlayer the player engine for advanced playback and rendering.

See Animated Image for more detailed information.

  • Objective-C
SDAnimatedImageView *imageView = [SDAnimatedImageView new];
SDAnimatedImage *animatedImage = [SDAnimatedImage imageNamed:@"image.gif"];
imageView.image = animatedImage;
  • Swift
let imageView = SDAnimatedImageView()
let animatedImage = SDAnimatedImage(named: "image.gif")
imageView.image = animatedImage

FLAnimatedImage integration has its own dedicated repo

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

Installation

There are four ways to use SDWebImage in your project:

  • using CocoaPods
  • using Carthage
  • using Swift Package Manager
  • manual install (build frameworks or embed Xcode Project)

Installation with CocoaPods

CocoaPods is a dependency manager for Objective-C, which automates and simplifies the process of using 3rd-party libraries in your projects. See the Get Started section for more details.

Podfile

platform :ios, '8.0'
pod 'SDWebImage', '~> 5.0'
Swift and static framework

Swift project previously had to use use_frameworks! to make all Pods into dynamic framework to let CocoaPods work.

However, starting with CocoaPods 1.5.0+ (with Xcode 9+), which supports to build both Objective-C && Swift code into static framework. You can use modular headers to use SDWebImage as static framework, without the need of use_frameworks!:

platform :ios, '8.0'
# Uncomment the next line when you want all Pods as static framework
# use_modular_headers!
pod 'SDWebImage', :modular_headers => true

See more on CocoaPods 1.5.0 โ€” Swift Static Libraries

If not, you still need to add use_frameworks! to use SDWebImage as dynamic framework:

platform :ios, '8.0'
use_frameworks!
pod 'SDWebImage'

Subspecs

There are 2 subspecs available now: Core and MapKit (this means you can install only some of the SDWebImage modules. By default, you get just Core, so if you need MapKit, you need to specify it).

Podfile example:

pod 'SDWebImage/MapKit'

Installation with Carthage

Carthage is a lightweight dependency manager for Swift and Objective-C. It leverages CocoaTouch modules and is less invasive than CocoaPods.

To install with carthage, follow the instruction on Carthage

Carthage users can point to this repository and use whichever generated framework they'd like: SDWebImage, SDWebImageMapKit or both.

Make the following entry in your Cartfile: github "SDWebImage/SDWebImage" Then run carthage update If this is your first time using Carthage in the project, you'll need to go through some additional steps as explained over at Carthage.

NOTE: At this time, Carthage does not provide a way to build only specific repository subcomponents (or equivalent of CocoaPods's subspecs). All components and their dependencies will be built with the above command. However, you don't need to copy frameworks you aren't using into your project. For instance, if you aren't using SDWebImageMapKit, feel free to delete that framework from the Carthage Build directory after carthage update completes.

Installation with Swift Package Manager (Xcode 11+)

Swift Package Manager (SwiftPM) is a tool for managing the distribution of Swift code as well as C-family dependency. From Xcode 11, SwiftPM got natively integrated with Xcode.

SDWebImage support SwiftPM from version 5.1.0. To use SwiftPM, you should use Xcode 11 to open your project. Click File -> Swift Packages -> Add Package Dependency, enter SDWebImage repo's URL. Or you can login Xcode with your GitHub account and just type SDWebImage to search.

After select the package, you can choose the dependency type (tagged version, branch or commit). Then Xcode will setup all the stuff for you.

If you're a framework author and use SDWebImage as a dependency, update your Package.swift file:

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

Manual Installation Guide

  • Check your command line Xcode version
sudo xcode-select -s /path/to/Xcode.app

or

export DEVELOPER_DIR=/path/to/Xcode.app/Contents/Developer
  • Run the script to build frameworks
./Scripts/build-frameworks.sh
  • Run the script to merge XCFramework
./Scripts/create-xcframework.sh
  • Use your own certificate to sign XCFramework
// https://developer.apple.com/support/third-party-SDK-requirements/
codesign --timestamp -v --sign "your own certificate" SDWebImage.xcframework

See more on wiki: Manual install Guide

Import headers in your source files

In the source files where you need to use the library, import the umbrella header file:

#import <SDWebImage/SDWebImage.h>

It's also recommend to use the module import syntax, available for CocoaPods(enable modular_headers)/Carthage/SwiftPM.

@import SDWebImage;

Build Project

At this point your workspace should build without error. If you are having problem, post to the Issue and the community can help you solve it.

Data Collection Practices

From Xcode 15, we provide the new PrivacyInfo.xcprivacy file for privacy details, see Describing data use in privacy manifests

You can exports the privacy report after archive your App by integrate SDWebImage via SwiftPM/XCFramework or CocoaPods (use_frameworks set to true).

For old version or if you're using static ar archive, as required by the App privacy details on the App Store, here's SDWebImage's list of Data Collection Practices.

Author

Collaborators

Credits

Thank you to all the people who have already contributed to SDWebImage.

Contributors

Licenses

All source code is licensed under the MIT License.

Architecture

To learn about SDWebImage's architecture design for contribution, read The Core of SDWebImage v5.6 Architecture. Thanks @looseyi for the post and translation.

High Level Diagram

Overall Class Diagram

Top Level API Diagram

Main Sequence Diagram

More detailed diagrams

sdwebimage's People

Contributors

adamwangxx avatar akhenakh avatar andybee avatar bpoplauschi avatar cbowns avatar dreampiggy avatar flovilmart avatar gsempe avatar ikesyo avatar insofan avatar jimmaye avatar jparise avatar kinarobin avatar klaaspieter avatar liulichao123 avatar matej avatar mattjgalloway avatar mythodeia avatar nonopolarity avatar oanapopescu avatar romanpodymov avatar rromanchuk avatar rs avatar seviu avatar skyline75489 avatar vyazovoy avatar walkline avatar whirlwind avatar zhongwuzw avatar zxiou 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  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  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  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

sdwebimage's Issues

Caching and SDNetworkActivityIndicator

My issue is in reference to using Kirby Turner's Photo Browser and SDNetworkActivityIndicator.

When scrolling through the Photo gallery, the first few photos were cached, and no activity indicator was necessary.

After an unknown index, (presumably where the cache stopped downloading?) the activity indicator shows on every photo swipe. Here is a video of the issue at hand: http://www.wrightscs.com/video/caching_issue.mov

I discovered this issue because I had to implement an indicator while images were downloading on 3G. The hud screen appears in place of the activity indicator, so this is my startActivity method:

- (void)startActivity
{
    @synchronized(self)
    {
        if (counter == 0)
        {
            [[NSNotificationCenter defaultCenter] postNotificationName:/*SDWebImageDownloadStartNotification*/@"startCaching" object:nil];
            [[UIApplication sharedApplication] setNetworkActivityIndicatorVisible:YES];
        }
        counter++;
    }
}

Without implementing anymore classes (i.e. the prefetch class), how can I show this indicator only when the images are downloading? Clearly in the video, the images are already downloaded when the indicator shows on every single swipe.

Image enlarges in cell after tap

Im using this to display images in a tableViewCell, but when I tap on the cell the image enlarges while the view changes to the detailView leaving the image awkward looking -_-'

Anyone else experienced this issue

No cancelation for disk query operation

Hi,

I have noticed that if some UIImageView switches between remote images quite fast, the SDImageCache don't have enough time to complete the following operation:

[cacheOutQueue addOperation:[[[NSInvocationOperation alloc] initWithTarget:self selector:@selector(queryDiskCacheOperation:) object:arguments] autorelease]];

before UIImageView, which is the final delegate, asks cache for image located on another URL, if the second request to cache is processed faster than this operation, so finally you get UIImageView setup with the 1st image got from disk.

You can easily check it in some synthetic test with quick filling UIImageView with images from different URLs. Or just check cancelation code, which never stops the already running NSOperation.

I may suggest to not to use NSInvocationOperation, but create your own subclass from NSOperation with correct 'isCancelled' processing.

get the image by byte[] for server

I want know how can use the SDWebImage,when the image not the url link.
I use like the following function to get the image:
-(void)getDocumentImages:(NSInteger)thePage
{

self.userName = [[NSUserDefaults standardUserDefaults] objectForKey:@"UserName"];
self.systemUrl = [[NSUserDefaults standardUserDefaults] objectForKey:@"SysUrl"];
NSURL *url = [NSURL URLWithString:[NSString stringWithFormat:@"http://%@/getDocmentimages",self.systemUrl]];
NSData *myPostData = [[NSString stringWithFormat:@"<documentInformationRequest><login_name>%@</login_name><document_id>%@</document_id><document_page>%d</document_page></documentInformationRequest>",self.userName,self.theDocID,thePage] dataUsingEncoding:NSUTF8StringEncoding];
[self setRequest:[ASIHTTPRequest requestWithURL:url]];
[self.request addRequestHeader:@"User-Agent" value:@"ASIHTTPRequest"];
NSMutableData *myMutablePostData = [NSMutableData dataWithData:myPostData];
[self.request setPostBody:myMutablePostData];
[self.request setTimeOutSeconds:60];
[self.request setRequestMethod:@"POST"];
[self.request addRequestHeader:@"Content-Type" value:@"application/xml"];
[self.request setDelegate:self];
[request setDidFinishSelector:@selector(requestForImageDone:)];
[request setDidFailSelector:@selector(requestWentWrong:)];
[request startAsynchronous];

}

  • (void)requestForImageDone:(ASIHTTPRequest *)theRequest{

    NSData *data = [theRequest responseData];
    UIImage *image = [UIImage imageWithData:data];
    }
    }

For that scene how toi use the SDwebimage?
actually i have a new ios developer,so i have any idea in cash.I need some one help. Thanks a lot

Image manipulation before caching

Hi,
not exactly an issue but more a feature request.
Where would it be the right place to do some offscreen (and possibily non in the main thread) image manipulation before storing to memcache and disk?

nice to have: toggle network status on/off

firt of all, great job! it's super easy to use, and performs caching nicely!

one feature i'd like to have: when asyn downloading image data for the first time, to toggle on network busy indicator on the status bar; toggle it off when image downloading finishes.

again, thanks a lot, it saves me a lot of time

Images never saved to disk store when SDWebImageRetryFailed option enabled

When SDWebImageRetryFailed option is enabled images are never stored to disk store

[manager downloadWithURL:url delegate:self options:SDWebImageRetryFailed];

In the following code:


- (void)imageDownloader:(SDWebImageDownloader *)downloader didFinishWithImage:(UIImage *)image
{
    [downloader retain];
...
    if (image)
    {
        // Store the image in the cache
        [[SDImageCache sharedImageCache] storeImage:image
                                          imageData:downloader.imageData
                                             forKey:[downloader.url absoluteString]
                                             toDisk:!(options & SDWebImageCacheMemoryOnly)];
    }
 ...
}

options & SDWebImageCacheMemoryOnly is always true

Changing the enumeration to a format suitable for bitwise operations solves the problem:


typedef enum
{
    SDWebImageOptionsNone = 0,
    SDWebImageRetryFailed = (1 <<  0),
    SDWebImageLowPriority = (1 << 1),
    SDWebImageCacheMemoryOnly = (1 << 2)
} SDWebImageOptions;

Lag when used with UIPageControl

Hi,

I am currently using SDWebImage to load images from a URL and display them as separate pages using UIPageControl. I am using the following code as it also does the caching.

[mageView setImageWithURL:[NSURL URLWithString:@"http://www.domain.com/path/to/image.jpg"]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

But I noticed that when I launch the app and start scrolling through the pages, there is a slight lag now after this implementation. But after I scroll through the pages and go back again to the first page, the lag is gone. Do you know the reason for this and how I can fix it?

Is there a limit on how many setImageWithURLs can be queued?

Hi, fantastic job on this library, by the way.

I'm wondering if there is an upper limit on how many setImageWithURL messages can be submitted at one time? I'm trying to load 100 photos and am looping through an array of URLs and submitting them like so:

[photoView.imageView setImageWithURL:[NSURL URLWithString:imageURL] placeholderImage:[UIImage imageNamed:@"photoDefault.png"]];

I'm listening for SDWebImageDownloadStartNotification and SDWebImageDownloadStopNotification events to "count" the number of times a download starts and finishes, and it's starting at 100 and counting down to 0, so it seems like it is working, but only about 25 of the images actually display up at a time. The rest remain the placeholder image.

I seem to remember reading a while back about a cache limit, but can't find it now. Just wondering if this is something intentional or (more likely) something I'm doing wrong in my code.

Thanks for any advice...

Setting the delegate for UIImageView (UIImageView+WebCache.h)

I think this may be a stupid question, but what I have is a ViewController with a UIImageView that is loading up an image from a URL using setImageWithURL, and that's working like a charm.

I have a UIActivityIndicator over the image, and I start it animating just before I make the call, and I'd like to stop it from animating when the download is complete (or fails)

I'd like to make my View Controller the delegate for the UIImageView (conforming to SDWebImageDownloaderDelegate so that I can be notified when the download is complete so I can do this.

How do I set the View controller to be the Image view's delegate? I was thinking that UIImageView+WebCache.h would have a delegate property I could set, but there isnt... am I totally missing something obvious here? I suspect I am...

Inform delegate about successful load

Hi,

I would like to be notified when SDWebImage successfully loaded an image (because then I can refresh a "reflection image view" with the new image). As far as I have seen this isn't possible yet but may be a feature some users might be interested in :-)

Crash in SDWebImageManager imageDownloader:didFinishWithImage:

We recently released our app to the appstore, and almost immediately got a few crashes in SDWebImageManager imageDownloader:didFinishWithImage:
The top of the stacks look like:

0 libobjc.A.dylib 0x33c28c98 objc_msgSend + 16
1 CoreFoundation 0x308f0571 -[NSObject(NSObject) performSelector:withObject:withObject:] + 25
2 Ourcode 0x0001d98f -SDWebImageManager imageDownloader:didFinishWithImage:
3 CoreFoundation 0x308f0571 -[NSObject(NSObject) performSelector:withObject:withObject:] + 25
4 Ourcode 0x0001cb03 -SDWebImageDownloader connectionDidFinishLoading:

We have the recent code that does a retain on the delegate inside this function.
As long as our delegate is created properly, I don't see how we get into this situation

Allocations keep increasing

Hi, thank you for this great library.

i am having problem hopefully you could put a light on me to solve this. on the instruments there is no leak however memory allocation keep increasing while rolling tableview which i filled with images. when i do stack trace as i can see this part causing problem.

http://tinyurl.com/8yblsya
http://tinyurl.com/7feewyt
http://tinyurl.com/7l5eqjk
http://tinyurl.com/bttl589

if ([delegate respondsToSelector:@selector(imageDownloader:didFinishWithImage:)])
{
    UIImage *image = [[UIImage alloc] initWithData:imageData];   //here %99

ifdef ENABLE_SDWEBIMAGE_DECODER

    [[SDWebImageDecoder sharedImageDecoder] decodeImage:image withDelegate:self userInfo:nil];

else

    [delegate performSelector:@selector(imageDownloader:didFinishWithImage:) withObject:self withObject:image];

endif

    [image release];
}

}

any help would be great.
many thanks.
-mohac.

Loading images without a table cell

I know I can load images directly using the manager but that means I need to handle the downloaded images inside a delegate, which is a bit of an annoyance when compared to the convenience provided for table cells.

I am not sure why it's limited to table cells since it's quite common to load images elsewhere. Wouldn't it be helpful if there were just a convenience method to load the images asynchronously and use them anywhere. For example just get the UIImage object back whether it's null or not and then place it inside a UIView or anywhere else with the placeholder image. The behavior would be similar to that for table cells except, it wouldn't force the use of table cells just to use this library and wouldn't require sending off the handling logic to a delegate which is cumbersome.

Generic data async download and caching

How much time would it take to hack this piece of code work with any data, fetching asynchronously and caching, therefore images would be a particular/common case?

SDWebImageManagerDelegate could return URL requested?

Hi,
thinking to use the image download as suggested in Using SDWebImageManager, wouldn't it be good to return also the requested NSURL?

  • (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image

If I use it in a class that implement the SDWebImageManagerDelegate protocol and I have multiple requests from different UIImage in my object, I have no way to understand which one has triggered the didFinishWithImage.

Am i wrong?
Thanks

Images not showing in TableViewCells until it scroll-down

First, thanks for this great project.

I'm facing an Issue occuring when I use UIImageView+WebCache category in a TableViewCell.

The issue is that first cells of the TableView are displaying the placeholder image and not the remote image (even if it's cached), until I scroll up or down the TableView itself.

The problem is that, when I have few cells I can't display any Image but only the placeholder.

Are there any workaround? Note that, when not in a TableView context the remote image is loaded correctly.

Cache preload

It would be neat to have a cache preload method on SDWebImageManager for downloading images to storage for later use. It should run the NSURLConnection in the standard NSEventTrackingRunLoopMode and not decode the downloaded image into a UIImage.

I've looked a bit at the source, but I'm a bit unsure how to best implement this.

Cache TTL

Locally I'm adding a way to set the setCacheMaxCacheAge on the singleton SDImageCache, which is a trivial change and works fine for my current use case, but it would be great if there were a way to set a time to live for each cache item as an extra param on setImageWithURL and to be able to set a default globally.

Allocations keep increasing in queryDiskCacheOperation method.

- (void)queryDiskCacheOperation:(NSDictionary *)arguments
{
    NSString *key = [arguments objectForKey:@"key"];
    NSMutableDictionary *mutableArguments = [[arguments mutableCopy] autorelease];

    UIImage *image = [[[UIImage alloc] initWithContentsOfFile:[self cachePathForKey:key]] autorelease];
    .......
}

There is steep increase in memory on this line --
[self cachePathForKey:key].

Please reslove this issue. I'm waiting for your reply.

Lazy loading with no-cache parameter, clearing the cache

SDWebImage is great. Very plug-and-play. Appreciated!

Two use-cases I'd like to see covered in the project:

  1. Ability to call SDWebImage for lazy-loading into UITableView with a parameter that prevents the image object from being cache. Example: For serving instream advertisements in a UITableView, I want to pull a fresh image every time. However, I still want to use SDWebImage because it provides simple lazyloading functionality.
  2. Simple method to clear the entire cache, and force all content to be reloaded.

Would the author consider adding these into the SDWebImage roadmap?

Again, great project - many thanks for distributing this!

Cached png images not transparent

I'm not sure if this is only an issue with my particular app, but it really seems like if I clear the cached images the following happens:

  1. they never load on the build that clears the cache
  2. on the next build they load with alpha transparency
  3. once they are cached, they load with white background where they were once transparent

For some background I am using the setImageWithURL method with a UITableView as follows:

[cell.imageView setImageWithURL:[NSURL URLWithString:theImagePath]
placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

Has anybody else experienced this?

Support for ALAssets

I've been working with the ALAssetsLibrary for the past few days, and it is really horrible in terms of (fast) asynchronous image fetching.

I've build a couple of classes inspired by SDWebImage to have proper caching and asynchronous image fetching.

Would it be interesting to have support for ALAssets built into SDWebImage? I'd find it very useful if I could provide an asset:// URL instead of a http:// URL and it would automatically retrieve the image from a singleton ALAssetsLibrary.

Looking forward to hearing what you guys think.

Glenn

Progress View

It would be great if you could add support for a UIProgressView so that when loading an image, the user can see the download progress. I'm trying to do it myself, but as I analyze the code, there are too many interdependencies that I can't figure out where to pass the progress indicator object to.

NSCache memory cache implementation instead of NSMutableDictionary

I see there is "LRU memory cache cleanup instead of reset on memory warning" in the roadmap.
I think, this issue can be done simpler using NSCache implementation for iOS >= 4.0. It's a faster and more clever way to boost the memory cache without doing any manual clean ups and LRU-logic on memory warnings.

[SDImageCache:storeImage:forKey] doesn't cache anything

i am using this method to save my image which is downloaded in other code.

but ,i noticed that in this function . it calls

[self storeImage:image imageData:nil forKey:key toDisk:YES];

in storeImage:imageData:forKey:toDisk
"
if (toDisk && !data)
{
return;
}

"
so the image will not stored. am i wrong? or incorrect usage.

Best practice for retrieving URL from didFinishWithImage?

Hello all, SDWebImage is working wonderfully for me. I'm currently using it to populate images into a Coverflow-esque object.

After looking through sources, I'm still attempting to determine how to retrieve the URL string for the image loaded after it triggers didFinishWithImage. Is this possible, if so, what would be the best method?

Store to disk

Hi,

I'm trying to store UIIMage to disk but it doesn't work. I look at the code and found :

  • (void)storeImage:(UIImage *)image imageData:(NSData *)data forKey:(NSString *)key toDisk:(BOOL)toDisk
    {
    if (!image || !key)
    {
    return;
    }

    [memCache setObject:image forKey:key];

    if (toDisk)
    {
    if (!data) return;
    NSArray *keyWithData;
    if (data)
    {
    keyWithData = [NSArray arrayWithObjects:key, data, nil];
    }
    else
    {
    keyWithData = [NSArray arrayWithObjects:key, nil];
    }
    [cacheInQueue addOperation:[[[NSInvocationOperation alloc] initWithTarget:self
    selector:@selector(storeKeyWithDataToDisk:)
    object:keyWithData] autorelease]];
    }
    }

I cannot understand the following test on data:

    if (!data) return;
    NSArray *keyWithData;
    if (data)
    {
        keyWithData = [NSArray arrayWithObjects:key, data, nil];
    }
    else

It has no meaning to me.

BTW the call to
[[SDImageCache sharedImageCache] storeImage:myImage forKey:myCacheKey];

and then to
[self storeImage:image imageData:nil forKey:key toDisk:YES];

result to ... nothing stored to disk because data is nil.

So at least your documentation is wrong and I must provide myself the imageData to the method:
storeImage: imageData: forKey: toDisk:

in order the image to be stored on disk.

Image looks corrupted on device

I'm using SDWebImage framework in my own apps happily two months, Some of my users complain about image quality.

But I'm fail to re-create the situation in my devices.

For example, I see one particular image[1] looks good but my client looks different[2] and I agree to him it looks like corrupted.

Devices, iOS versions are same and if I use NSURLConnection to download image, it looks good on client side device.

Therefore, I suspect it may be related to SDWebImage, but as you can see, there is no error or sth like that, so I can not trace it.

[1] http://imgur.com/skoGl
[2] http://imgur.com/Phmkj

Can anyone at least suggest a way to trace this problem?

format detection ?

when caching png with transparency, their are cached to disk as jpg and the transparency is removed :x

SDWebImage and SDURLCache

Hi,

it seems that the SDURLCache cache doesn't work with SDWebImage because in SDWebImageDownloader :

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];

To make it works I'm using :

NSURLRequest *request = [[NSURLRequest alloc] initWithURL:url cachePolicy:NSURLRequestUseProtocolCachePolicy timeoutInterval:15];

Maybe it could exist some configuration to enable the SDURLCache ?

iOS 5 ARC

Hi, there is any iOS5 ARC update of your helper?
Thanks in advance.

Problem with placeholderImage

I have created an PNG image with a transparent background and use this as a placeholder image. Sometimes (not ever) is ready downloaded image overlaps with the placeholder image. So i have my target Image im background of my placeholder image. Is this a known problem or am I doing something wrong?

Disk cache size limit by application folder size?

Is it worth to let us control the size limit of disk cache by folder size, say 200MB (instead of days). So any oldest images will be deleted to save disk spaces. This may be useful to some photo viewing app. Any thoughts

UIImageView content mode is not respected when loading image.

I have tested all morning why images are "Centered" when I explicitly set the content mode to AspectFit.

imageView.contentMode = UIViewContentModeScaleAspectFit;

if (!useSDWebImage) {
    imageView.image = [UIImage imageWithData:[NSData dataWithContentsOfURL:[NSURL URLWithString:stringURL]]];
}
else{
    [imageView setImageWithURL:[NSURL URLWithString:stringURL]];
}

Using the above code I have verified that using SDWebImage is what is causing the sizing error, as only when I use SDWEbImage I notice the content mode is not respected.

Any ideas as to what might be going on?

Don't use url for cache key

Hi,

Great library, I use it often. I have discovered a problem in one of my apps: some images changed on the website, but still use the same URL. Because the image cache uses that url (which didn't change), the user always sees the same old image.

Would it be possible to either use some sort of md5 hash for the cache key? Or something like this, where I can set a different cache key?

[[SDWebImageManager sharedManager] 
    downloadWithURL:image_url 
    useCacheKey:news_title 
    delegate:self
];

With something like this, it would download the new image for a new news item, even if the image url would've been "re-used" on the site.

Useless mutitasking device check in SDImageCache.m

I think the device check is useless because due to the #if, the code will be executed on iOS4 device only, on this OS version the key UIApplicationDidEnterBackgroundNotification is defined, and the notification will be sent only on devices that are multitasking capable.

if __IPHONE_OS_VERSION_MIN_REQUIRED >= __IPHONE_4_0

    UIDevice *device = [UIDevice currentDevice];
    if ([device respondsToSelector:@selector(isMultitaskingSupported)] && device.multitaskingSupported)
    {
        // When in background, clean memory in order to have less chance to be killed
        [[NSNotificationCenter defaultCenter] addObserver:self
                                                 selector:@selector(clearMemory)
                                                     name:UIApplicationDidEnterBackgroundNotification
                                                   object:nil];
    }

endif

Cheers

Autorelease problem

Hi,

When I use the SDWebImage library to load my images into a UITableView I keep getting these messages on the console output:

2011-05-06 15:21:46.167 MyApp[604:9d43] *** __NSAutoreleaseNoPool(): Object 0x10dae0 of class UIImage autoreleased with no pool in place - just leaking

How can I fix this?

Improvement for NSURL

When user is sending a string instead of NSURL object, the string not always conforms to RFC 2396, this is why it's better to apply some string conversions before creating the NSURL, like:
[NSURL URLWithString:[myStringLink stringByAddingPercentEscapesUsingEncoding:NSUTF8StringEncoding]];

Thank you.

SDImageCache storeImage:forKey always does nothing

When invoking storeImage:forKey on SDImageCache the method storeImage:imageData:forKey:toDisk is called with the following arguments: storeImage: imageData:nil forKey toDisk:YES.
Inside the method storeImage:imageData:forKey:toDisk there is a condition that passes if imageData is nil and toDisk is YES, and returns, so the method eventually does nothing.

i have created an PNG image with a transparent background and use this as a placeholder image.its shows Dark background on images in default UITableViewCell. Dont know what is the issue i have change the code in UIImageView+WebCache.h for having activit

i have created an PNG image with a transparent background and use this as a placeholder image.its shows Dark background on images in default UITableViewCell. Dont know what is the issue i have change the code in UIImageView+WebCache.h for having activity indicator

#import "UIImageView+WebCache.h"

#define kCustomRowHeight  80.0
#define kAppIconHeight   50
#define kCustomRowHeightipad  80.0
#define kAppIconHeightipad   120

@implementation UIImageView (WebCache)

- (void)setImageWithURL:(NSURL *)url
{
    [self setImageWithURL:url placeholderImage:nil];
}

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder
{
    [self setImageWithURL:url placeholderImage:placeholder options:0];
}

- (void)setImageWithURL:(NSURL *)url placeholderImage:(UIImage *)placeholder options:(SDWebImageOptions)options
{
    SDWebImageManager *manager = [SDWebImageManager sharedManager];

    // Remove in progress downloader from queue
    [manager cancelForDelegate:self];

    self.image = placeholder;
    self.alpha = 1;



    UIActivityIndicatorView *activityIndicator = (UIActivityIndicatorView*)[self viewWithTag:1001];

    if (activityIndicator == nil) {

        activityIndicator = [[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray];

        activityIndicator.tag = 1001;

        if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {
            activityIndicator.frame=CGRectMake(0, 0, 70, 70);
            activityIndicator.center = CGPointMake(42.0f,50.0f);
        }
        else{
            activityIndicator.center = CGPointMake(21.5f,21.5f);
        }
         [self addSubview:activityIndicator];

        [activityIndicator startAnimating];
    }

    else {

        [activityIndicator startAnimating];    
    }


    if (url)
    {
        [manager downloadWithURL:url delegate:self options:options];
    }
}

- (void)cancelCurrentImageLoad
{
    UIView *activityIndicator = [self viewWithTag:1001];
    [activityIndicator removeFromSuperview];
    [[SDWebImageManager sharedManager] cancelForDelegate:self];
}

- (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image
{
    if (UI_USER_INTERFACE_IDIOM() == UIUserInterfaceIdiomPad) {

            CGSize itemSize = CGSizeMake(kAppIconHeightipad, kAppIconHeightipad);
            UIGraphicsBeginImageContextWithOptions(itemSize, YES, 0);
            CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
            [image drawInRect:imageRect];
            UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            self.image=newImage;

    }
    else
    {
            CGSize itemSize = CGSizeMake(kAppIconHeight, kAppIconHeight);
            UIGraphicsBeginImageContextWithOptions(itemSize, YES, 0);
            CGRect imageRect = CGRectMake(0.0, 0.0, itemSize.width, itemSize.height);
            [image drawInRect:imageRect];
            UIImage* newImage = UIGraphicsGetImageFromCurrentImageContext();
            UIGraphicsEndImageContext();
            self.image=newImage;

    }
    UIView *activityIndicator = [self viewWithTag:1001];
    [activityIndicator removeFromSuperview];
}

@end

SEE THE IMAGE U WILL GET IT

http://www.filejumbo.com/Download/8604C4259887534B

I WANT IMAGE

http://www.filejumbo.com/Download/9F12F348B6D52C3A

Thanks in Advance
Pradeeo Jha

SDWebImageDownloader should judge the MIMEType

Hi
I noticed that when I use a image set URL with image but return MIMEType is text/html,
It jump to - (void)connection:(NSURLConnection *)aConnection didReceiveData:(NSData *)data

and then jump to the UIImageView+WebCache.m - (void)webImageManager:(SDWebImageManager *)imageManager didFinishWithImage:(UIImage *)image method.

if i take the SDWebImageManagerDelegate - (void)webImageManager:(SDWebImageManager *)imageManager didFailWithError:(NSError *)error; in UIImageView+WebCache.m , it not call.

so I think in SDWebImageDownloader.m should override the NSURLConnectionDataDelegate 's - (void)connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response method and judge the MIMEType.

I provide this URL(http://www.iteeyan.com/wp-content/uploads/2011/cqtravel/cq-travel-panxiyanxian-xichang04-00.jpg) for test.

This is my first time to new issue, if wrong, please forgive me.

Typos in README

In the section "Using SDWebImageManager", the method when implementing the "SDWebImageManagerDelegate" is wrong, it should be "webImageManager:didFinishWithImage:" instead of "imageHelper:didFinishWithImage:".

Anyway, great project !!!

the UITableViewCells imageView becomes bigger when selected?

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    static NSString *MyIdentifier = @"MyIdentifier";

    UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:MyIdentifier];

    if (cell == nil)
    {
        cell = [[[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault
                                       reuseIdentifier:MyIdentifier] autorelease];
    }

    // Here we use the new provided setImageWithURL: method to load the web image
    [cell.imageView setImageWithURL:[NSURL URLWithString:@"http://xxx.com/image.jpg"]
                   placeholderImage:[UIImage imageNamed:@"placeholder.png"]];

    cell.textLabel.text = @"My Text";
    return cell;
}

http://xxx.com/image.jpg is bigger than the cell image bounds,and placeholder.png is also bigger than the cell img,
when i selected the cell,the cell image becomes bigger,am i wrong?

SDWebImageManager.didNotFindImageForKey will increment delegates and downloaders array when didFailWithError will occure

It seems that you should handle didFailWithError in the SDWebImageManager class to remove the delegate and downloader. When you try to load a image several times via the same UIImageView and you always receive a "unhandled" didFailWithError with every new trial of getting the image the delegates and downloader array will increment:

[delegates addObject:delegate];
[downloaders addObject:downloader];

So if you you try to load a image two times the array has two items inside. If the second call is getting a didFinishWithImage back you will call
[delegate performSelector:@selector(webImageManager:didFinishWithImage:) withObject:self withObject:image];
two times...

It seems you have to remove them as you do in the didFinishWithImage method...

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.