iOS如何獲取網絡圖片(二)


ios如何獲取圖片(二)無沙盒下

解決問題

*解決問題1:tableView滑動卡頓,圖片延時加載
解決方法:添加異步請求,在子線程里請求網絡,在主線程刷新UI

*解決問題2:反復請求網絡圖片,增加用戶流量消耗
解決方法:創建了downloadImage,downloadImage屬於數據源,當tableview滾動的時候就可以給cell的數據賦值,運用了MVC設計方式

*解決問題3:當沒有請求到圖片時,留白影響用戶體驗,圖片還會延時刷新
解決方法:添加默認圖片

*解決問題4:當該cell的網絡請求未執行完,又滾動到了該cell,會導致網絡請求重復
解決方法:創建網絡請求緩沖池

*解決問題5:當出現數量較多的圖片時,防止內存使用過多,耦合性大
解決方法:創建圖片緩沖池

代碼如下圖

    - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {

    SXTShopCell * cell = [tableView dequeueReusableCellWithIdentifier:identifier];

    SXTShop * shop = self.dataList[indexPath.row];

    cell.shop = shop;

    //為了避免重復加載的問題,創建了downloadImage,downloadImage屬於數據源,當tableview滾動的時候就可以給cell的數據賦值

    //從圖片緩沖池里找到對應的圖片
    if ([self.imageCache objectForKey:shop.shop_image]) {
    
    //如果下載過,直接從內存中獲取圖片
    cell.iconView.image = shop.downloadImage;
    cell.iconView.image = self.imageCache[shop.shop_image];
    
     } else {
    
        //設置默認圖片
        cell.iconView.image = [UIImage imageNamed:@"defaultImage"];
    
        [self downloadImage:indexPath];
 
     }

return cell;
}

- (void)downloadImage:(NSIndexPath *)indexPath {

    SXTShop * shop = self.dataList[indexPath.row];

    if ([self.operationDict objectForKey:shop.shop_image]) {
    
        NSLog(@"已經請求過了,請等待下載");
    
    } else {
        
    
        //如果未下載過,開啟異步線程
        NSBlockOperation * op = [NSBlockOperation blockOperationWithBlock:^{
        
            //模擬網絡延時
            [NSThread sleepForTimeInterval:1];
        
        //通過url獲取網絡數據
            NSData * data = [NSData dataWithContentsOfURL:[NSURL URLWithString:[NSString                  stringWithFormat:@"%@%@",baseUrl,shop.shop_image]]];
        
            //將數據裝換為圖片
            UIImage * image = [UIImage imageWithData:data];
        
            //如果有圖片
            if (image) {
            
                //通知model,將圖片賦值給downloadImage,以便下次從內存獲取
                //                    shop.downloadImage = image;
            
                //將圖片作為value,將url作為key
               [self.imageCache setObject:image forKey:shop.shop_image];
            
            //獲取主隊列,更新UI
                [[NSOperationQueue mainQueue] addOperationWithBlock:^{
                
                //刷新第indexPath單元的表格
                [self.tableView reloadRowsAtIndexPaths:@[indexPath]         withRowAnimation:UITableViewRowAnimationNone];
                
            }];
        }
    }];
    
    //將請求加入操作緩沖池中
    [self.operationDict setObject:op forKey:shop.shop_image];
    
    //將請求加入全局隊列
    [self.queue addOperation:op];
    }


}

//當內存發生警報時,調用
- (void)didReceiveMemoryWarning {
[super didReceiveMemoryWarning];
// Dispose of any resources that can be recreated.

    [self.imageCache removeAllObjects];
    [self.operationDict removeAllObjects];

    [self.queue cancelAllOperations];
}


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM