在多媒體相關的 App 裡,讀取使用者相簿中的照片與影片幾乎是必經之路。這篇文章直接上程式碼,示範如何透過 ALAssetsLibrary 遍歷相簿,並進一步把資產 URL 轉換成可實際存取、可傳輸的檔案。
先定義幾個常用路徑常數,方便後續把原圖與影片寫入沙盒:
#import <AssetsLibrary/AssetsLibrary.h> // 照片原圖路徑 #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]
接著在 MainViewController 中遍歷所有相簿群組與資產。這裡有一個關鍵細節:所有 UI 更新都必須切回主執行緒,否則在子執行緒排隊更新畫面會非常緩慢。
@implementation MTHMainViewController
- (void)viewDidLoad {
[super viewDidLoad];
self.navigationItem.title = @"Demo";
self.view.backgroundColor = [UIColor clearColor];
self.groupArrays = [NSMutableArray array];
self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"測試" style:UIBarButtonItemStylePlain target:self action:@selector(testRun)];
UIPanGestureRecognizer *panRecognizer = [[UIPanGestureRecognizer alloc] initWithTarget:self action:@selector(didClickPanGestureRecognizer:)];
[self.navigationController.view addGestureRecognizer:panRecognizer];
self.litimgView = [[UIImageView alloc] initWithFrame:CGRectMake(100, 200, 120, 120)];
[self.view addSubview:_litimgView];
}
- (void)testRun {
__weak MTHMainViewController *weakSelf = self;
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
ALAssetsLibraryGroupsEnumerationResultsBlock listGroupBlock = ^(ALAssetsGroup *group, BOOL *stop) {
if (group != nil) {
[weakSelf.groupArrays addObject:group];
} else {
[weakSelf.groupArrays enumerateObjectsUsingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
[obj enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) {
if ([result thumbnail] != nil) {
if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) {
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);
// UI的更新記得放在主線程
dispatch_async(dispatch_get_main_queue(), ^{
self.litimgView.image = image;
});
} else if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo]) {
// 和圖片方法類似
}
}
}];
}];
}
};
ALAssetsLibraryAccessFailureBlock failureBlock = ^(NSError *error) {
NSString *errorMessage = nil;
switch ([error code]) {
case ALAssetsLibraryAccessUserDeniedError:
case ALAssetsLibraryAccessGloballyDeniedError:
errorMessage = @"用戶拒絕訪問相冊,請在<隱私>中開啟";
break;
default:
errorMessage = @"Reason unknown.";
break;
}
dispatch_async(dispatch_get_main_queue(), ^{
UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"錯誤,無法訪問!" message:errorMessage delegate:self cancelButtonTitle:@"確定" otherButtonTitles:nil, nil];
[alertView show];
});
};
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:listGroupBlock failureBlock:failureBlock];
});
}
但要注意:用上面方法直接取出的路徑是無法傳輸的,必須先把它轉化成 NSData 物件,再重新寫入沙盒路徑。以下分別示範圖片與影片的轉存做法。
// 將原始圖片的URL轉化為NSData數據,寫入沙盒
- (void)imageWithUrl:(NSURL *)url withFileName:(NSString *)fileName {
// 進這個方法的時候也應該加判斷,如果已經轉化了的就不要調用這個方法了
// 如何判斷已經轉化了,通過是否存在文件路徑
ALAssetsLibrary *assetLibrary = [[ALAssetsLibrary alloc] init];
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); // 沒到結尾,沒出錯,繼續
}
free(buffer);
buffer = NULL;
fclose(file);
file = NULL;
}
} failureBlock:nil];
}
});
}
影片之所以採用 1MB 緩衝區分塊讀寫,而不是像圖片那樣一次性配對等大小的記憶體,正是為了避免面對大型影片時佔用過量記憶體。這一點在實作時值得特別留意。