您现在的位置: IOS教程網 >> IOS系統 >  >> iOS 程式開發 >> iOS 開發綜合

iOS 相冊開發:AssetsLibrary 與 PhotoKit 使用梳理

編輯:iOS 開發綜合

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

一、AssetsLibrary 的組成

AssetsLibrary 的結構與相冊本身相似,主要包含以下物件:

  • ALAssetsLibrary:代表整個設備的資源庫。
  • ALAssetsGroup:代表一個相冊。
  • ALAsset:代表一張照片或一段影片。
  • ALAssetRepresentation:封裝資源內容,方便讀取圖片、影片與檔案資訊。

二、遍歷相冊與資源

使用 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 轉為可保存的檔案

相冊資源的 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];
}

四、PhotoKit 簡述

在 iOS 8 之後,PhotoKit 提供了更完整的相冊操作能力。常用物件包括:

  • PHAsset:代表一張照片或一段影片。
  • PHAssetCollection:代表一個相冊。
  • PHImageManager:用於從資源取得圖片。
  • PHImageRequestOptions:設定圖片請求選項。

如果需要同時取得多張圖片,可以透過 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);
        }];
    }
}
  1. 上一篇文章:
  2. 下一篇文章:
蘋果刷機越獄教程| IOS教程問題解答| IOS技巧綜合| IOS7技巧| IOS8教程
Copyright © IOS教程網 All Rights Reserved