Sdwebimage as the most popular image download third-party framework, the use rate is very high. But are you really going to use it? This article will then take an example to analyze how to use sdwebimage rationally. Use the scene: The custom UITableViewCell has the picture need to display, asks the network network status is the WiFi, displays the picture high definition image, when the network status is the cellular network, displays the picture thumbnail. As an example:
- In order to listen to the network status, here I recommend the use of afnetworking.
- Import a third-party framework afnetworking on GitHub or use Cocoapod for the project.
- Listen for network status in the Application:didfinishlaunchingwithoptions: method in the APPDELEGATE.M file.
// AppDelegate.m 文件中- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // 监控网络状态 [[AFNetworkReachabilityManager sharedManager] startMonitoring];}// 以下代码在需要监听网络状态的方法中使用AFNetworkReachabilityManager *mgr = [AFNetworkReachabilityManager sharedManager]; if (mgr.isReachableViaWiFi) // 在使用Wifi, 下载原图 else // 其他,下载小图 } }
- Then there will be an iOS learner complaining: Isn't that easy? So rinsed finished writing the following code.
//using MVC, when setting the cell's model properties, download the image-SetItem: (Customitem *) item{_item = Item;UIImage*placeholder = [UIImageimagenamed:@"Placeholderimage"]; Afnetworkreachabilitymanager *mgr = [Afnetworkreachabilitymanager Sharedmanager];if(Mgr. Isreachableviawifi) {//When using WiFi, download the original[ Self. ImageViewsd_setimagewithurl:[NsurlUrlwithstring:item. Originalimage] Placeholderimage:placeholder]; }Else{//Other, download small map[ Self. ImageViewsd_setimagewithurl:[NsurlUrlwithstring:item. Thumbnailimage] Placeholderimage:placeholder]; }}
-
At this point, it is really possible to complete the basic download the corresponding image according to the current network status, but in real development, this is actually unreasonable. Here are some details to keep in mind:
- Sdwebimage automatically helps in the development of cached images (including memory caches, sandbox caches), so we need to set the user to download in the
WiFi environment, and the 高清图 next time the 蜂窝网络状态 app opens, it should be displayed 高清图 instead of downloading thumbnails.
- Many application settings modules come with one function:
移动网络环境下仍然显示高清图 . This feature is actually set record in the sandbox, about the data saved to the local, you can view my other brief book home article
iOS local data access, see here is enough
- The business cannot be handled properly when the user is offline.
-
So, we started to improve. To make it easier for the reader to understand, I'll post the pseudocode:
-SetItem: (Customitem *) item{_iTEM = Item;if(The original is in the cache) { Self. imageview.image = original; }Else{if(WiFi environment) {Download Display original}Else if(mobile phone comes with network) {if(3G\4G Environment still download the original image) {Download display original}Else{Download show small Image}}Else{if(There is a small image in the cache) { Self. imageview.image = Small map; }Else //Processing offline status{ Self. imageview.image = placeholder picture; } } }}
- Implement the above pseudo-code: The reader can correspond to the above pseudo-code. Recommended in practice
先写伪代码 , then write real code
- A lot of attention to
注释 explanations.
-SetItem: (Customitem *) item{_item = Item;//Placeholder Pictures UIImage*placeholder = [UIImageimagenamed:@"Placeholderimage"];//Get the original image from the memory \ Sandbox cache, UIImage*originalimage = [[Sdimagecache Sharedimagecache] Imagefromdiskcacheforkey:item. Originalimage];if(Originalimage) {//If the memory \ Sandbox cache has an original image, then the original image is displayed directly (no matter what network status is present) Self. ImageView. Image= Originalimage; }Else{//memory \ Sandbox Cache No originalAfnetworkreachabilitymanager *mgr = [Afnetworkreachabilitymanager Sharedmanager];if(Mgr. Isreachableviawifi) {//When using WiFi, download the original[ Self. ImageViewsd_setimagewithurl:[NsurlUrlwithstring:item. Originalimage] Placeholderimage:placeholder]; }Else if(Mgr. Isreachableviawwan) {//Use your phone to bring your own network //user's configuration items are assumed to be stored in a sandbox using Nsuserdefaults //[[Nsuserdefaults standarduserdefaults] setbool:no forkey:@ "Alwaysdownloadoriginalimage"]; //[[Nsuserdefaults standarduserdefaults] synchronize];#warning Read the user's configuration items from the sandbox: whether the original image is still downloaded in the 3G\4G environment BOOLAlwaysdownloadoriginalimage = [[NsuserdefaultsStandarduserdefaults] boolforkey:@"Alwaysdownloadoriginalimage"];if(Alwaysdownloadoriginalimage) {//Download the original[ Self. ImageViewsd_setimagewithurl:[NsurlUrlwithstring:item. Originalimage] Placeholderimage:placeholder]; }Else{//Download Small image[ Self. ImageViewsd_setimagewithurl:[NsurlUrlwithstring:item. Thumbnailimage] Placeholderimage:placeholder]; } }Else{//No network UIImage*thumbnailimage = [[Sdimagecache Sharedimagecache] Imagefromdiskcacheforkey:item. Thumbnailimage];if(thumbnailimage) {//memory \ Sandbox cache with small image Self. ImageView. Image= Thumbnailimage; }Else{//Handle offline status, and there is no caching situation Self. ImageView. Image= placeholder; } } }}
Has it been solved? The real pit is only just beginning.
- Before we describe the hole in the code above, let's analyze the caching mechanism of UITableViewCell.
- See: There is a tableview
同时 displaying three UITableViewCell, each tableViewCell containing a imageview child control, and each cell has a 对应的模型属性 picture content that is used to set the ImageView.
注意: The cache pool is empty because no cell is pushed out of the screen.
-
When a cell is pushed out of the screen, the cell is automatically placed in the automatic cache pool. 注意: The cell's uiimage image data model is not emptied! Or a cell that is used up.
-
When the next cell enters the screen, the system will find the corresponding cell according to the logo registered by TableView, and apply it. The cell entered into the buffer pool is added to the 重新 TableView, and the cell data is set in the TableView's tableView: cellForRowAtIndexPath: DataSource method 对应的模型 , when the cell corresponds to the
- The above is a brief introduction to the TableView reuse mechanism.
Back again, so where is the real pit above?
- Use a scene to describe it: when the user's environment WiFi speed
不够快 (not immediately after the download of the picture), and in the above code, in the WiFi environment is also downloaded high-definition large image. So you need 一定的时间 to complete the download. At this point, the user is reluctant to wait, want to see 上次打开 the app when the picture displayed, the user will slide to be in 下面的cell to view. Note: 此时,上面的cell下载图片操作并没有暂停,还在处于下载图片状态中 . When the user is viewing 上次打开App the displayed picture (the last time the app downloaded the completed picture, Sdwebimage will help us cache, do not download), and just need to display 上次打开App时的图片 the cell is the use of TableView 重用机制 from the cache pool of cells, Wait until 上面的cell the high-definition large image has been downloaded, sdwebimage the default approach is to immediately set the downloaded image to ImageView, so we will be at the bottom of the display cell display above the image, resulting in 数据错乱 , this is a very serious bug.
So how do you solve this thorny problem?
- If we were able to remove the cell before it was put in the buffer pool when it was taken out of the cache, there would be
下载操作 no data confusion.
- At this point you may ask me: How do I remove the download operation? Download operation is not sdwebimage to help us do it?
- That's right, it is sdwebimage to help us download pictures, we have to grilled a Sdwebimage source code to see how he was completed.
- (void) Sd_setimagewithurl: (Nsurl*) URL Placeholderimage: (UIImage*) Placeholder options: (sdwebimageoptions) Options Progress: (Sdwebimagedownloaderprogressblock) Progressblock Completed: (sdwebimagecompletionblock) Completedblock {//Close the download of the current picture[ SelfSd_cancelcurrentimageload]; Objc_setassociatedobject ( Self, &imageurlkey, URL, objc_association_retain_nonatomic);if(! (Options & Sdwebimagedelayplaceholder)) {Dispatch_main_async_safe (^{ Self. Image= placeholder; }); }if(URL) {//Check if ActivityView is enabled or not if([ SelfShowactivityindicatorview]) {[ SelfAddactivityindicator]; } __Weak__typeof ( Self) Wself = Self;ID<SDWebImageOperation> operation = [Sdwebimagemanager. SharedmanagerDownloadimagewithurl:url options:options Progress:progressblock completed:^ (UIImage*image,Nserror*error, Sdimagecachetype CacheType,BOOLFinished,Nsurl*imageurl) {[Wself removeactivityindicator];if(!wself)return; Dispatch_main_sync_safe (^{if(!wself)return;if(Image && (Options & sdwebimageavoidautosetimage) && Completedblock) {Completedblock (image, error, cachetype, URL);return; }Else if(image) {wself. Image= Image; [Wself Setneedslayout]; }Else{if(Options & Sdwebimagedelayplaceholder) {wself. Image= placeholder; [Wself Setneedslayout]; } }if(Completedblock && finished) {Completedblock (image, error, cachetype, URL); } }); }]; [ SelfSd_setimageloadoperation:operation forkey:@"Uiimageviewimageload"]; }Else{Dispatch_main_async_safe (^{[ SelfRemoveactivityindicator];if(Completedblock) {Nserror*error = [NserrorErrorwithdomain:sdwebimageerrordomain code:-1Userinfo:@{nslocalizeddescriptionkey: @"Trying to load a nil url"}]; Completedblock (Nil, error, Sdimagecachetypenone, URL); } }); }}
We are surprised to find that the original sdwebimage when downloading pictures, the first thing is to close imageview current download operation!
- Does it start to sigh sdwebimage how magical? Yes, we just have to write the code we wrote all the direct access to the local cache code using Sdwebimage to set it OK!
- Here is the complete version of the code.
-SetItem: (Customitem *) item{_item = Item;//Placeholder Pictures UIImage*placeholder = [UIImageimagenamed:@"Placeholderimage"];//Get the original from memory \ Sandbox cache UIImage*originalimage = [[Sdimagecache Sharedimagecache] Imagefromdiskcacheforkey:item. Originalimage];if(Originalimage) {//If the memory \ Sandbox cache has an original image, then the original image is displayed directly (no matter what network status is present)[ Self. ImageViewsd_setimagewithurl:[NsurlUrlwithstring:item. Originalimage] Placeholderimage:placeholder]; }Else{//memory \ Sandbox Cache No originalAfnetworkreachabilitymanager *mgr = [Afnetworkreachabilitymanager Sharedmanager];if(Mgr. Isreachableviawifi) {//When using WiFi, download the original[ Self. ImageViewsd_setimagewithurl:[NsurlUrlwithstring:item. Originalimage] Placeholderimage:placeholder]; }Else if(Mgr. Isreachableviawwan) {//Use your phone to bring your own network //user's configuration items are assumed to be stored in a sandbox using Nsuserdefaults //[[Nsuserdefaults standarduserdefaults] setbool:no forkey:@ "Alwaysdownloadoriginalimage"]; //[[Nsuserdefaults standarduserdefaults] synchronize];#warning Read the user's configuration items from the sandbox: whether the original image is still downloaded in the 3G\4G environment BOOLAlwaysdownloadoriginalimage = [[NsuserdefaultsStandarduserdefaults] boolforkey:@"Alwaysdownloadoriginalimage"];if(Alwaysdownloadoriginalimage) {//Download the original[ Self. ImageViewsd_setimagewithurl:[NsurlUrlwithstring:item. Originalimage] Placeholderimage:placeholder]; }Else{//Download Small image[ Self. ImageViewsd_setimagewithurl:[NsurlUrlwithstring:item. Thumbnailimage] Placeholderimage:placeholder]; } }Else{//No network UIImage*thumbnailimage = [[Sdimagecache Sharedimagecache] Imagefromdiskcacheforkey:item. Thumbnailimage];if(thumbnailimage) {//memory \ Sandbox cache with small image[ Self. ImageViewsd_setimagewithurl:[NsurlUrlwithstring:item. Thumbnailimage] Placeholderimage:placeholder]; }Else{ [ Self. ImageViewSd_setimagewithurl:NilPlaceholderimage:placeholder]; } } }}
This article describes here, if you have any questions or errors, you are welcome to point out. Like just a little attention to it.
iOS development-Do you really use sdwebimage?