在 iOS 8 之前,開發者主要使用 AssetsLibrary 存取設備相冊。iOS 8 之後,蘋果推出 PhotoKit,提供更現代化的照片與影片存取方式。本文將重點整理 AssetsLibrary 的使用方式,並補充 PhotoKit 的基本概念。
AssetsLibrary 的結構與相冊本身相似,主要包含以下物件:

使用 AssetsLibrary 時,通常先取得所有相冊,再逐一取出其中的資源。
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary enumerateGroupsWithTypes:ALAssetsGroupAll
usingBlock:^(ALAssetsGroup *group, BOOL *stop) {
if (group == nil) {
return;
}
[group enumerateAssetsUsingBlock:^(ALAsset *asset, NSUInteger index, BOOL *stop) {
if (asset == nil) {
return;
}
NSString *type = [asset valueForProperty:ALAssetPropertyType];
if ([type isEqualToString:ALAssetTypePhoto]) {
UIImage *thumbnail = [UIImage imageWithCGImage:[asset thumbnail]];
NSURL *url = [[asset defaultRepresentation] url];
NSLog(@"照片 URL:%@", url);
} else if ([type isEqualToString:ALAssetTypeVideo]) {
NSURL *url = [[asset defaultRepresentation] url];
NSLog(@"影片 URL:%@", url);
}
}];
} failureBlock:^(NSError *error) {
NSLog(@"無法存取相冊:%@", error.localizedDescription);
}];相冊資源的 URL 並不適合直接作為對外傳輸的檔案路徑。實務上通常需要將資源內容轉存到 App 的沙盒目錄。
- (void)saveImageWithURL:(NSURL *)url fileName:(NSString *)fileName {
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary assetForURL:url
resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *representation = [asset defaultRepresentation];
Byte *buffer = (Byte *)malloc((unsigned long)representation.size);
NSUInteger buffered = [representation getBytes:buffer
fromOffset:0.0
length:((unsigned long)representation.size)
error:nil];
NSData *data = [NSData dataWithBytesNoCopy:buffer
length:buffered
freeWhenDone:YES];
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *filePath = [cachesPath stringByAppendingPathComponent:fileName];
[data writeToFile:filePath atomically:YES];
} failureBlock:nil];
}對於影片,不建議一次配置完整檔案大小的記憶體。實務上可以分段讀取,再逐步寫入檔案。
- (void)saveVideoWithURL:(NSURL *)url fileName:(NSString *)fileName {
ALAssetsLibrary *assetsLibrary = [[ALAssetsLibrary alloc] init];
[assetsLibrary assetForURL:url
resultBlock:^(ALAsset *asset) {
ALAssetRepresentation *representation = [asset defaultRepresentation];
NSString *cachesPath = [NSSearchPathForDirectoriesInDomains(NSCachesDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSString *videoPath = [cachesPath stringByAppendingPathComponent:fileName];
FILE *file = fopen([videoPath UTF8String], "a+");
if (file == NULL) {
return;
}
const int bufferSize = 1024 * 1024;
Byte *buffer = (Byte *)malloc(bufferSize);
NSUInteger read = 0;
NSUInteger offset = 0;
NSError *error = nil;
do {
read = [representation getBytes:buffer
fromOffset:offset
length:bufferSize
error:&error];
if (read > 0) {
fwrite(buffer, sizeof(char), read, file);
offset += read;
}
} while (read != 0 && error == nil);
free(buffer);
fclose(file);
} failureBlock:nil];
}在 iOS 8 之後,PhotoKit 提供了更完整的相冊操作能力。常用物件包括:
如果需要同時取得多張圖片,可以透過 PHFetchResult 取得資源列表,再逐一請求圖片。
PHFetchResult *collections = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeAlbum
subtype:PHAssetCollectionSubtypeAlbumRegular
options:nil];
for (PHAssetCollection *collection in collections) {
PHFetchResult *assets = [PHAsset fetchAssetsInAssetCollection:collection options:nil];
for (PHAsset *asset in assets) {
[[PHImageManager defaultManager] requestImageForAsset:asset
targetSize:CGSizeZero
contentMode:PHImageContentModeDefault
options:nil
resultHandler:^(UIImage *result, NSDictionary *info) {
NSLog(@"取得圖片:%@", result);
}];
}
}