溫馨提示×

溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊×
其他方式登錄
點擊 登錄注冊 即表示同意《億速云用戶服務(wù)條款》

怎么在iOS中利用多線程實現(xiàn)多圖下載功能

發(fā)布時間:2021-05-22 16:55:03 來源:億速云 閱讀:196 作者:Leah 欄目:移動開發(fā)

這篇文章將為大家詳細(xì)講解有關(guān)怎么在iOS中利用多線程實現(xiàn)多圖下載功能,文章內(nèi)容質(zhì)量較高,因此小編分享給大家做個參考,希望大家閱讀完這篇文章后對相關(guān)知識有一定的了解。

一.模型文件代碼如下

// XMGAPP.h 
 
#import <Foundation/Foundation.h> 
 
@interface XMGAPP : NSObject 
 
/** APP的名稱 */ 
@property (nonatomic, strong) NSString *name; 
/** APP的圖片的url地址 */ 
@property (nonatomic, strong) NSString *icon; 
/** APP的下載量 */ 
@property (nonatomic, strong) NSString *download; 
 
+(instancetype)appWithDict:(NSDictionary *)dict; 
@end
// XMGAPP.m 
 
#import "XMGAPP.h" 
 
@implementation XMGAPP 
 
+(instancetype)appWithDict:(NSDictionary *)dict 
{ 
  XMGAPP *appM = [[XMGAPP alloc]init]; 
  //KVC 
  [appM setValuesForKeysWithDictionary:dict]; 
   
  return appM; 
} 
@end

控制器.m代碼如下:

// ViewController.m 
 
#import "ViewController.h" 
#import "XMGAPP.h" 
 
@interface ViewController () 
/** tableView的數(shù)據(jù)源 */ 
@property (nonatomic, strong) NSArray *apps; 
/** 內(nèi)存緩存 */ 
@property (nonatomic, strong) NSMutableDictionary *images; 
/** 隊列 */ 
@property (nonatomic, strong) NSOperationQueue *queue; 
/** 操作緩存 */ 
@property (nonatomic, strong) NSMutableDictionary *operations; 
@end 
 
@implementation ViewController 
 
#pragma mark ---------------------- 
#pragma mark lazy loading 
-(NSOperationQueue *)queue 
{ 
  if (_queue == nil) { 
    _queue = [[NSOperationQueue alloc]init]; 
    //設(shè)置最大并發(fā)數(shù) 
    _queue.maxConcurrentOperationCount = 5; 
  } 
  return _queue; 
} 
-(NSMutableDictionary *)images 
{ 
  if (_images == nil) { 
    _images = [NSMutableDictionary dictionary]; 
  } 
  return _images; 
} 
-(NSArray *)apps 
{ 
  if (_apps == nil) { 
     
    //字典數(shù)組 
    NSArray *arrayM = [NSArray arrayWithContentsOfFile:[[NSBundle mainBundle]pathForResource:@"apps.plist" ofType:nil]]; 
     
    //字典數(shù)組---->模型數(shù)組 
    NSMutableArray *arrM = [NSMutableArray array]; 
    for (NSDictionary *dict in arrayM) { 
      [arrM addObject:[XMGAPP appWithDict:dict]]; 
    } 
    _apps = arrM; 
  } 
  return _apps; 
} 
 
-(NSMutableDictionary *)operations 
{ 
  if (_operations == nil) { 
    _operations = [NSMutableDictionary dictionary]; 
  } 
  return _operations; 
} 
 
#pragma mark ---------------------- 
#pragma mark UITableViewDatasource 
-(NSInteger)numberOfSectionsInTableView:(UITableView *)tableView 
{ 
  return 1; 
} 
 
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section 
{ 
  return self.apps.count; 
} 
 
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath 
{ 
  static NSString *ID = @"app"; 
   
  //1.創(chuàng)建cell 
  UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:ID]; 
   
  //2.設(shè)置cell的數(shù)據(jù) 
  //2.1 拿到該行cell對應(yīng)的數(shù)據(jù) 
  XMGAPP *appM = self.apps[indexPath.row]; 
   
  //2.2 設(shè)置標(biāo)題 
  cell.textLabel.text = appM.name; 
   
  //2.3 設(shè)置子標(biāo)題 
  cell.detailTextLabel.text = appM.download; 
   
  //2.4 設(shè)置圖標(biāo) 
   
  //先去查看內(nèi)存緩存中該圖片時候已經(jīng)存在,如果存在那么久直接拿來用,否則去檢查磁盤緩存 
  //如果有磁盤緩存,那么保存一份到內(nèi)存,設(shè)置圖片,否則就直接下載 
  //1)沒有下載過 
  //2)重新打開程序 
   
  UIImage *image = [self.images objectForKey:appM.icon]; 
  if (image) { 
    cell.imageView.image = image; 
    NSLog(@"%zd處的圖片使用了內(nèi)存緩存中的圖片",indexPath.row) ; 
  }else 
  { 
    //保存圖片到沙盒緩存 
    NSString *caches = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) lastObject]; 
    //獲得圖片的名稱,不能包含/ 
    NSString *fileName = [appM.icon lastPathComponent]; 
    //拼接圖片的全路徑 
    NSString *fullPath = [caches stringByAppendingPathComponent:fileName]; 
     
     
    //檢查磁盤緩存 
    NSData *imageData = [NSData dataWithContentsOfFile:fullPath]; 
    //廢除 
    imageData = nil; 
     
    if (imageData) { 
      UIImage *image = [UIImage imageWithData:imageData]; 
      cell.imageView.image = image; 
       
      NSLog(@"%zd處的圖片使用了磁盤緩存中的圖片",indexPath.row) ; 
      //把圖片保存到內(nèi)存緩存 
      [self.images setObject:image forKey:appM.icon]; 
       
//      NSLog(@"%@",fullPath); 
    }else 
    { 
      //檢查該圖片時候正在下載,如果是那么久什么都捕捉,否則再添加下載任務(wù) 
      NSBlockOperation *download = [self.operations objectForKey:appM.icon]; 
      if (download) { 
         
      }else 
      { 
         
        //先清空cell原來的圖片 
        cell.imageView.image = [UIImage imageNamed:@"Snip20160221_306"]; 
         
        download = [NSBlockOperation blockOperationWithBlock:^{ 
          NSURL *url = [NSURL URLWithString:appM.icon]; 
          NSData *imageData = [NSData dataWithContentsOfURL:url]; 
          UIImage *image = [UIImage imageWithData:imageData]; 
           
           NSLog(@"%zd--下載---",indexPath.row); 
           
          //容錯處理 
          if (image == nil) { 
            [self.operations removeObjectForKey:appM.icon]; 
            return ; 
          } 
          //演示網(wǎng)速慢的情況 
          //[NSThread sleepForTimeInterval:3.0]; 
         
          //把圖片保存到內(nèi)存緩存 
          [self.images setObject:image forKey:appM.icon]; 
           
          //NSLog(@"Download---%@",[NSThread currentThread]); 
          //線程間通信 
          [[NSOperationQueue mainQueue] addOperationWithBlock:^{ 
             
            //cell.imageView.image = image; 
            //刷新一行 
            [self.tableView reloadRowsAtIndexPaths:@[indexPath] withRowAnimation:UITableViewRowAnimationLeft]; 
            //NSLog(@"UI---%@",[NSThread currentThread]); 
          }]; 
           
           
          //寫數(shù)據(jù)到沙盒 
          [imageData writeToFile:fullPath atomically:YES]; 
           
          //移除圖片的下載操作 
          [self.operations removeObjectForKey:appM.icon]; 
           
        }]; 
         
        //添加操作到操作緩存中 
        [self.operations setObject:download forKey:appM.icon]; 
         
        //添加操作到隊列中 
        [self.queue addOperation:download]; 
      } 
       
    } 
  } 
   
  //3.返回cell 
  return cell; 
} 
 
-(void)didReceiveMemoryWarning 
{ 
  [self.images removeAllObjects]; 
   
  //取消隊列中所有的操作 
  [self.queue cancelAllOperations]; 
} 
 
//1.UI很不流暢 --- > 開子線程下載圖片 
//2.圖片重復(fù)下載 ---> 先把之前已經(jīng)下載的圖片保存起來(字典) 
//內(nèi)存緩存--->磁盤緩存 
 
//3.圖片不會刷新--->刷新某行 
//4.圖片重復(fù)下載(圖片下載需要時間,當(dāng)圖片還未完全下載之前,又要重新顯示該圖片) 
//5.數(shù)據(jù)錯亂 ---設(shè)置占位圖片 
 
/* 
 Documents:會備份,不允許 
 Libray 
  Preferences:偏好設(shè)置 保存賬號 
  caches:緩存文件 
 tmp:臨時路徑(隨時會被刪除) 
 */ 
 
@end

關(guān)于怎么在iOS中利用多線程實現(xiàn)多圖下載功能就分享到這里了,希望以上內(nèi)容可以對大家有一定的幫助,可以學(xué)到更多知識。如果覺得文章不錯,可以把它分享出去讓更多的人看到。

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點不代表本網(wǎng)站立場,如果涉及侵權(quán)請聯(lián)系站長郵箱:is@yisu.com進(jìn)行舉報,并提供相關(guān)證據(jù),一經(jīng)查實,將立刻刪除涉嫌侵權(quán)內(nèi)容。

ios
AI