你好,歡迎來到IOS教程網

 Ios教程網 >> IOS編程開發 >> IOS開發綜合 >> iOS-獲取本地相冊的所有圖片展示在cell上

iOS-獲取本地相冊的所有圖片展示在cell上

編輯:IOS開發綜合

iOS-獲取本地相冊的所有圖片展示在cell上。

1.下載MJExtension 數據轉模型庫

2.自定義cell 大致布局如下

大致實現的效果如下 《我適配橫屏了 大家可隨意》

讓TableView支持橫屏的代碼如下:

//支持橫屏

myTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;

\

 

基礎知識

現在iOS9之後用#import 這個框架 據說更為強大 稍後有時間我會研究研究一下貼出來給大家看一下

首先用到了這幾個框架 這是iOS9以下的框架和類

#import

#import

#import

#import

重要方法

// 將原始圖片的URL轉化為NSData數據,寫入沙盒

- (void)imageWithUrl:(NSURL *)url withFileName:(NSString *)fileName

{

// 進這個方法的時候也應該加判斷,如果已經轉化了的就不要調用這個方法了

// 如何判斷已經轉化了,通過是否存在文件路徑

ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];

// 創建存放原始圖的文件夾--->OriginalPhotoImages

NSFileManager * fileManager = [NSFileManager defaultManager];

if (![fileManager fileExistsAtPath:KOriginalPhotoImagePath]) {

[fileManager createDirectoryAtPath:KOriginalPhotoImagePath withIntermediateDirectories:YES attributes:nil error:nil];

}

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

if (url) {

// 主要方法

[assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {

ALAssetRepresentation *rep = [asset defaultRepresentation];

Byte *buffer = (Byte*)malloc((unsigned long)rep.size);

NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:((unsigned long)rep.size) error:nil];

NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];

NSString * imagePath = [KOriginalPhotoImagePath stringByAppendingPathComponent:fileName];

[data writeToFile:imagePath atomically:YES];

 

 

} failureBlock:nil];

}

});

}

// 將原始視頻的URL轉化為NSData數據,寫入沙盒

- (void)videoWithUrl:(NSURL *)url withFileName:(NSString *)fileName

{

// 解析一下,為什麼視頻不像圖片一樣一次性開辟本身大小的內存寫入?

// 想想,如果1個視頻有1G多,難道直接開辟1G多的空間大小來寫?

ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{

if (url) {

[assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {

ALAssetRepresentation *rep = [asset defaultRepresentation];

NSString * videoPath = [KCachesPath stringByAppendingPathComponent:fileName];

char const *cvideoPath = [videoPath UTF8String];

FILE *file = fopen(cvideoPath, "a+");

if (file) {

const int bufferSize = 1024 * 1024;

// 初始化一個1M的buffer

Byte *buffer = (Byte*)malloc(bufferSize);

NSUInteger read = 0, offset = 0, written = 0;

NSError* err = nil;

if (rep.size != 0)

{

do {

read = [rep getBytes:buffer fromOffset:offset length:bufferSize error:&err];

written = fwrite(buffer, sizeof(char), read, file);

offset += read;

} while (read != 0 && !err);//沒到結尾,沒出錯,ok繼續

}

// 釋放緩沖區,關閉文件

free(buffer);

buffer = NULL;

fclose(file);

file = NULL;

}

} failureBlock:nil];

}

});

}

我們的照片存在本地相冊取得時候得出來的是ALAssetsGroup這個類裡面的數據 需要我們把圖片寫入沙河Cache目錄中 然後再進行操作 代碼全部在我的Git中 想學習的可以下載下來看一下 以下是我VC裡面的所有代碼 注釋的很清楚 大家可以看一下 另外本文此Demo我已上傳至Git 歡迎大家的

#import "ViewController.h"
#import 
#import 
#import 
#import 
#import 
#import "YY_FileTableViewCell.h"
#import "MJExtension.h"
#import "Model.h"
#import 
// 照片原圖路徑
#define KOriginalPhotoImagePath   \
[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"OriginalPhotoImages"]

// 視頻URL路徑
#define KVideoUrlPath   \
[[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"VideoURL"]

// caches路徑
#define KCachesPath   \
[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0]

@interface ViewController ()
{
    UITableView  *myTableView;
    NSMutableArray *imagesList;
    NSMutableArray *timeStringList;
    NSMutableArray *locationStringList;
    NSMutableArray *locationLists;
    NSMutableArray *models;
    NSMutableArray *locationsModels;
    CLGeocoder *geocoder;
}

 @end

@implementation ViewController

- (void)viewWillAppear:(BOOL)animated{
    
    [super viewWillAppear:animated];
    
    [self getAllPhotosFromSystemPhotosLibrary];
    
    self.view.backgroundColor = [UIColor whiteColor];
    
    self.edgesForExtendedLayout = UIRectEdgeNone;
    
    self.view.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    
}
- (void)viewDidLoad {
    
    [super viewDidLoad];
    
    imagesList = [NSMutableArray array];
    
    timeStringList = [NSMutableArray array];
    
    locationStringList = [NSMutableArray array];
    
    models = [NSMutableArray array];
    
    locationsModels = [NSMutableArray array];
    
    locationLists = [NSMutableArray array];
    
    geocoder = [[CLGeocoder alloc]init];
    
    [self loadUI];
}

- (void)loadUI{
    
    myTableView = [[UITableView alloc]initWithFrame:self.view.frame style:UITableViewStylePlain];
    myTableView.delegate = self;
    myTableView.rowHeight = 100;
    myTableView.dataSource = self;
    //支持橫屏
    myTableView.autoresizingMask = UIViewAutoresizingFlexibleHeight|UIViewAutoresizingFlexibleWidth;
    
    [self.view addSubview:myTableView];
    /*
     34.3830750000 Latitude
     114.2750620000 Longitude
     */
    //測試
}

#pragma mark ======獲取到系統相冊的所有圖片=======
- (NSString *)stringFromDate:(NSDate *)date{
    
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    
    //zzz表示時區,zzz可以刪除,這樣返回的日期字符將不包含時區信息。
    
    [dateFormatter setDateFormat:@"yyyy-MM-dd HH:mm:ss"];
    
    
    NSString *destDateString = [dateFormatter stringFromDate:date];
    
    
    return destDateString;
    
}

- (NSString *)returnPlaceStringLatitudeText:(NSString *)LatitudeText LongtitudeText:(NSString *)LongtitudeText{
    
    //dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);
    
    CLLocation *location = [[CLLocation alloc]initWithLatitude:[LatitudeText doubleValue] longitude:[LongtitudeText doubleValue]];
    
    __block NSString *place;
    
    [geocoder reverseGeocodeLocation:location completionHandler:^(NSArray * _Nullable placemarks, NSError * _Nullable error) {
        
        if (error||placemarks.count==0) {
            
            place = @"未知的位置";
            
            NSLog(@"%@",place);
            
        }
        else{
            
            place = placemarks.firstObject.name;
            
            NSLog(@"%@",place);
        }
        
    }];

    return place;
}

//獲取相冊裡的所有圖片
- (void)getAllPhotosFromSystemPhotosLibrary{
    /*
    
    NSString *paths = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:@"OriginalPhotoImages"];
    
    NSLog(@"paths%@",paths);
    
    如果本地存儲的路徑裡有 則讀取本地的目錄的 如果沒有則讀取相冊裡的
    
    if (paths) {
        
        NSFileManager *fm = [NSFileManager defaultManager];
        
        //獲取目錄下圖片的所有名字 比如說IMG_0004.JPG
        NSArray *files = [fm subpathsAtPath:paths];
        
        for (NSString *fileName in files) {
            
            NSLog(@"%@",fileName);
            
            NSString *path = [[NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:[NSString stringWithFormat:@"OriginalPhotoImages/%@",fileName]];
            
            UIImage *image = [UIImage imageWithContentsOfFile:path];
            
            NSLog(@"image = %@",image);
            
            [imagesList addObject:image];
        }
    
    }
    */
    ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc]init];//生成整個photolibrary的實例
    
    [assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOL *stop) {//獲取所有group
        [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
            //從group裡面
            NSString* assetType = [result valueForProperty:ALAssetPropertyType];
            
            if ([assetType isEqualToString:ALAssetTypePhoto]) {
                //NSLog(@"Photo");
                NSDate *date= [result valueForProperty:ALAssetPropertyDate];
                UIImage *image = [UIImage imageWithCGImage:[result thumbnail]];
                NSString *fileName = [[result defaultRepresentation] filename];
                NSURL *url = [[result defaultRepresentation] url];
                NSDictionary *dict = [[result defaultRepresentation]metadata];
                
                //int64_t fileSize = [[result defaultRepresentation] size];
                /*
                 2016-06-27 13:55:17.024 Share_First[2941:1062832] Photo
                 2016-06-27 13:55:17.029 Share_First[2941:1062832] date = 2011-03-13 00:17:25 +0000
                 2016-06-27 13:55:17.030 Share_First[2941:1062832] fileName = IMG_0001.JPG
                 2016-06-27 13:55:17.030 Share_First[2941:1062832] url = assets-library://asset/asset.JPG?id=106E99A1-4F6A-45A2-B320-B0AD4A8E8473&ext=JPG
                 2016-06-27 13:55:17.030 Share_First[2941:1062832] fileSize = 1896240
                 */
                //NSLog(@"元數據=%@",dict);
                //NSLog(@"date = %@",date);//照片拍攝時間
                //NSLog(@"fileName = %@",fileName);//照片名稱
                //NSLog(@"url = %@",url);//照片文件URL(非網絡URL 浏覽器上輸入這個URL找不到這張圖片 我試了)
                //NSLog(@"fileSize = %lld",fileSize);//照片文件size 具體單位不知道是什麼 肯定不是MshareImageView
                
                //latitude:緯度
                //longitude:經度
                
                NSString *Longitude = dict[@"{GPS}"][@"Longitude"];
                NSString *Latitude  = dict[@"{GPS}"][@"Latitude"];
                
                if (Longitude==nil||Latitude==nil) {
                    Longitude = @"";
                    Latitude  = @"";
                }
                
                NSLog(@"longitude= %@ Latitude = %@",Longitude,Latitude);
                
                [locationLists addObject:@{@"Longitude":Longitude,@"Latitude":Latitude}];
                
                locationsModels = [Model mj_objectArrayWithKeyValuesArray:locationLists];
                
                [timeStringList addObject:@{@"timeString":[self stringFromDate:date]}];
                
                models = [Model mj_objectArrayWithKeyValuesArray:timeStringList];
                
                [imagesList addObject:image];
  
                //讀取完照片之後寫入APP沙河cache目錄  這個方法我在網上找到的
                
                [self imageWithUrl:url withFileName:fileName];
                
                //回到主線程更新UI
                dispatch_async(dispatch_get_main_queue(), ^{
                    
                    [myTableView reloadData];
                });
             }else if([assetType isEqualToString:ALAssetTypeVideo]){
                
                NSLog(@"Video");
                
                NSDate *date= [result valueForProperty:ALAssetPropertyDate];
                UIImage *image = [UIImage imageWithCGImage:[result thumbnail]];
                NSString *fileName = [[result defaultRepresentation] filename];
                NSURL *url = [[result defaultRepresentation] url];
                int64_t fileSize = [[result defaultRepresentation] size];
                NSLog(@"date = %@",date);
                NSLog(@"fileName = %@",fileName);
                NSLog(@"url = %@",url);
                NSLog(@"fileSize = %lld",fileSize);
                NSLog(@"image = %@",image);
                
                [self videoWithUrl:url withFileName:fileName];
                
            }else if([assetType isEqualToString:ALAssetTypeUnknown]){
                NSLog(@"Unknow AssetType");
            }
            //-----------可解開----------
            /*
            NSDictionary *assetUrls = [result valueForProperty:ALAssetPropertyURLs];
            
            for (NSString *assetURLKey in assetUrls) {
                
                NSLog(@"%@",[assetUrls objectForKey:assetURLKey]);
                
            }
            */
        }];
    } failureBlock:^(NSError *error) {
        NSLog(@"Enumerate the asset groups failed.");
    }];
        
    
}
// 將原始圖片的URL轉化為NSData數據,寫入沙盒
- (void)imageWithUrl:(NSURL *)url withFileName:(NSString *)fileName
{
    // 進這個方法的時候也應該加判斷,如果已經轉化了的就不要調用這個方法了
    // 如何判斷已經轉化了,通過是否存在文件路徑
    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
    // 創建存放原始圖的文件夾--->OriginalPhotoImages
    NSFileManager * fileManager = [NSFileManager defaultManager];
    if (![fileManager fileExistsAtPath:KOriginalPhotoImagePath]) {
        [fileManager createDirectoryAtPath:KOriginalPhotoImagePath withIntermediateDirectories:YES attributes:nil error:nil];
    }
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (url) {
            // 主要方法
            [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
                ALAssetRepresentation *rep = [asset defaultRepresentation];
                Byte *buffer = (Byte*)malloc((unsigned long)rep.size);
                NSUInteger buffered = [rep getBytes:buffer fromOffset:0.0 length:((unsigned long)rep.size) error:nil];
                NSData *data = [NSData dataWithBytesNoCopy:buffer length:buffered freeWhenDone:YES];
                NSString * imagePath = [KOriginalPhotoImagePath stringByAppendingPathComponent:fileName];
                [data writeToFile:imagePath atomically:YES];
                
                
            } failureBlock:nil];
        }
    });
}
// 將原始視頻的URL轉化為NSData數據,寫入沙盒
- (void)videoWithUrl:(NSURL *)url withFileName:(NSString *)fileName
{
    // 解析一下,為什麼視頻不像圖片一樣一次性開辟本身大小的內存寫入?
    // 想想,如果1個視頻有1G多,難道直接開辟1G多的空間大小來寫?
    ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        if (url) {
            [assetLibrary assetForURL:url resultBlock:^(ALAsset *asset) {
                ALAssetRepresentation *rep = [asset defaultRepresentation];
                NSString * videoPath = [KCachesPath stringByAppendingPathComponent:fileName];
                char const *cvideoPath = [videoPath UTF8String];
                FILE *file = fopen(cvideoPath, "a+");
                if (file) {
                    const int bufferSize = 1024 * 1024;
                    // 初始化一個1M的buffer
                    Byte *buffer = (Byte*)malloc(bufferSize);
                    NSUInteger read = 0, offset = 0, written = 0;
                    NSError* err = nil;
                    if (rep.size != 0)
                    {
                        do {
                            read = [rep getBytes:buffer fromOffset:offset length:bufferSize error:&err];
                            written = fwrite(buffer, sizeof(char), read, file);
                            offset += read;
                        } while (read != 0 && !err);//沒到結尾,沒出錯,ok繼續
                    }
                    // 釋放緩沖區,關閉文件
                    free(buffer);
                    buffer = NULL;
                    fclose(file);
                    file = NULL;
                }
            } failureBlock:nil];
        }
    });
}

/*
- (void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
 {
       // 1.判斷平台是否可用
        if (![SLComposeViewController isAvailableForServiceType:SLServiceTypeSinaWeibo]) {
                 NSLog(@"平台不可用,或者沒有配置相關的帳號");
                 return;
             }
    
         // 2.創建分享的控制器
         SLComposeViewController *composeVc = [SLComposeViewController composeViewControllerForServiceType:SLServiceTypeSinaWeibo];
    
        // 2.1.添加分享的文字
           [composeVc setInitialText:@"我是一個codeMan"];
    
         // 2.2.添加一個圖片
         [composeVc addImage:[UIImage imageNamed:@"xingxing"]];
    
         // 2.3.添加一個分享的鏈接
         [composeVc addURL:[NSURL URLWithString:@"www.baidu.com"]];
    
         // 3.彈出分享控制器
         [self presentViewController:composeVc animated:YES completion:nil];
    
         // 4.監聽用戶點擊了取消還是發送
         composeVc.completionHandler = ^(SLComposeViewControllerResult result) {
                 if (result == SLComposeViewControllerResultCancelled) {
                         NSLog(@"點擊了取消");
                     } else {
                             NSLog(@"點擊了發送");
                         }
             };
 
 }
*/
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    
    return  models.count;
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    YY_FileTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:[YY_FileTableViewCell ID]];;
    if (!cell) {
        cell = [YY_FileTableViewCell YY_FileTableViewCell];
    }
    cell.block = ^(YY_FileTableViewCell *cell){
        //點擊按鈕的時候調用
        NSIndexPath *path = [tableView indexPathForCell:cell];
        NSLog(@"組%ld 行%ld ",path.section,path.row);
    };
    Model *model = models[indexPath.row];
    Model *model1 = locationsModels[indexPath.row];
    
    NSLog(@"Latitude = %@",model1.Latitude);
    NSLog(@"Longitude = %@",model1.Longitude);
    
    cell.Longtitude = model1.Longitude;
    cell.Latitude   = model1.Latitude;
    
    cell.timeLabel.adjustsFontSizeToFitWidth = YES;
    cell.locationLabel.adjustsFontSizeToFitWidth = YES;
    
    cell.timeLabel.text = model.timeString;
    
    cell.shareImageView.image = imagesList[indexPath.row];
    
    cell.locationLabel.text = [NSString stringWithFormat:@"緯度 = %@ 經度 = %@",model1.Latitude,model1.Longitude];
    
    return cell;
}
- (void)didReceiveMemoryWarning {
    
    [super didReceiveMemoryWarning];
    
    // Dispose of any resources that can be recreated.
}

@end 
代碼方法沒有太多的封裝~寫的有點亂 大家見諒 另外大家如有對本文有更好的建議和理解記得comment我一下~我們相互學習!
  1. 上一頁:
  2. 下一頁:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © Ios教程網 All Rights Reserved