ios ALAssetsLibrary簡單的使用


關於ALAssetsLibrary的簡單使用有兩個方面:

第一:存儲圖片/視頻方法如下:

// With a UIImage, the API user can use -[UIImage CGImage] to get a CGImageRef, and cast -[UIImage imageOrientation] to ALAssetOrientation.
- (void)writeImageToSavedPhotosAlbum:(CGImageRef)imageRef orientation:(ALAssetOrientation)orientation completionBlock:(ALAssetsLibraryWriteImageCompletionBlock)completionBlock;
//
The API user will have to specify the orientation key in the metadata dictionary to preserve the orientation of the image - (void)writeImageToSavedPhotosAlbum:(CGImageRef)imageRef metadata:(NSDictionary *)metadata completionBlock:(ALAssetsLibraryWriteImageCompletionBlock)completionBlock // If there is a conflict between the metadata in the image data and the metadata dictionary, the image data metadata values will be overwritten - (void)writeImageDataToSavedPhotosAlbum:(NSData *)imageData metadata:(NSDictionary *)metadata completionBlock:(ALAssetsLibraryWriteImageCompletionBlock)completionBlock // - (void)writeVideoAtPathToSavedPhotosAlbum:(NSURL *)videoPathURL completionBlock:(ALAssetsLibraryWriteVideoCompletionBlock)completionBlock

簡單說明:

orientation為儲存圖片時的具體操作:

typedef NS_ENUM(NSInteger, ALAssetOrientation) {
    ALAssetOrientationUp                 // default orientation 默認方向
    ALAssetOrientationDown             // 180 deg rotation
    ALAssetOrientationLeft              // 90 deg CCW
    ALAssetOrientationRight               // 90 deg CW
    ALAssetOrientationUpMirrored          // as above but image mirrored along other axis. horizontal flip 鏡像
    ALAssetOrientationDownMirrored      // horizontal flip
    ALAssetOrientationLeftMirrored        // vertical flip
    ALAssetOrientationRightMirrored      // vertical flip
}

metadata為元數據內容,如果內容和圖片內部沖突,將覆蓋操作;

第二:獲取圖片/視頻

以下方法中是異步獲取相冊內容:

// Get the list of groups that match the given types. Multiple types can be ORed together. The results are passed one by one to the caller by executing the enumeration block.
// When the enumeration is done, 'enumerationBlock' will be called with group set to nil.
// When groups are enumerated, the user may be asked to confirm the application's access to the data. If the user denies access to the application or if no application is allowed to access the data, the failure block will be called.
// If the data is currently unavailable, the failure block will be called.
- (void)enumerateGroupsWithTypes:(ALAssetsGroupType)types usingBlock:(ALAssetsLibraryGroupsEnumerationResultsBlock)enumerationBlock failureBlock:(ALAssetsLibraryAccessFailureBlock)failureBlock 

ALAssetsGroupType參數解析如下:

ALASSetsGroupType: 類型 ALAssetsGroupLibrary:從iTunes 來的相冊內容。

ALAssetsGroupAlbum:設備自身產生或從iTunes同步來的照片,但是不包括照片流跟分享流 中的照片。(例如從各個軟件中保存下來的圖片)

ALAssetsGroupEvent 相機接口事件產生的相冊
ALAssetsGroupFaces 臉部相冊(具體不清楚)
ALAssetsGroupSavedPhotos 相機膠卷照片
ALAssetsGroupPhotoStream 照片流
ALAssetsGroupAll 除了ALAssetsGroupLibrary上面所的內容。

獲得組別后 對組別進行操作:

//組封面
- (CGImageRef)posterImage

//組別個數

- (NSInteger)numberOfAssets
//約束
- (void)setAssetsFilter:(ALAssetsFilter *)filter
//枚舉
- (void)enumerateAssetsUsingBlock:(ALAssetsGroupEnumerationResultsBlock)enumerationBlock - (void)enumerateAssetsWithOptions:(NSEnumerationOptions)options usingBlock:(ALAssetsGroupEnumerationResultsBlock)enumerationBlock - (void)enumerateAssetsAtIndexes:(NSIndexSet *)indexSet options:(NSEnumerationOptions)options usingBlock:(ALAssetsGroupEnumerationResultsBlock)enumerationBlock

參數說明:

ALAssetsFilter:

+ (ALAssetsFilter *)allPhotos;
+ (ALAssetsFilter *)allVideos;
+ (ALAssetsFilter *)allAssets;

NSEnumerationOptions:正反排序

NSIndexSet:組中第N個

對於ALAsset的說明:

方法:

  - (CGImageRef)thumbnail

  - (CGImageRef)aspectRatioThumbnail

  - (ALAssetRepresentation *)defaultRepresentation

  Representation屬性:

  – CGImageWithOptions:

  – fullResolutionImage(完全分辨率的圖片)

  – fullScreenImage(滿屏的圖片

  - (id)valueForProperty:(NSString *)property

property:

    1.ALAssetPropertyType 資源的類型(照片,視頻)

      2.ALAssetPropertyLocation 資源地理位置(無位置信息返回null)

      3.ALAssetPropertyDuation 播放時長(照片返回ALErorInvalidProperty)

      4.ALAssetPropertyOrientation 方向(共有8個方向,參見:ALAssetOrientation)

      5.ALAssetPropertyDate 拍攝時間(包含了年與日時分秒)

      6.ALAssetPropertyRepresentations 描述(打印看了下,只有帶后綴的名稱)

      7.ALAssetPropertyURLs(返回一個字典,鍵值分別是文件名和文件的url)

      8.ALAssetPropertyAssetURL 文件的url )

    editable  property(指示資源是否可以編輯,只讀屬性)

    originalAsset  property(原始資源。若沒有保存修改后資源,則原始資源為nil)

我的代碼:

 

-(void)getAllPicturesAndVideo
{
    //失敗控制
    ALAssetsLibraryAccessFailureBlock failureblock =
    ^(NSError *myerror)
    {
        NSLog(@"相冊訪問失敗 =%@", [myerror localizedDescription]);
        if ([myerror.localizedDescription rangeOfString:@"Global denied access"].location!=NSNotFound) {
            NSLog(@"無法訪問相冊.請在'設置->定位服務'設置為打開狀態.");
        }else{
            NSLog(@"相冊訪問失敗.");
        }
        return ;
    };
    mutableArray =[[NSMutableArray alloc]init];
  //成功 ALAssetsLibraryGroupsEnumerationResultsBlock libraryGroupsEnumeration
=
  ^(ALAssetsGroup* group,BOOL* stop){
   //說明枚舉結束用group==nil標識
if (group!=nil) { [mutableArray addObject:group]; } else { NSLog(@"%ld",mutableArray.count);
         //更新UI } }; [[ViewController defaultAssetsLibrary] enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:libraryGroupsEnumeration failureBlock:failureblock]; }

 

//從組別中獲取第index個數據
[group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:index] options:NSEnumerationConcurrent usingBlock:^(ALAsset *result, NSUInteger index, BOOL *stop) { //圖片 if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypePhoto]) { UIImage *image=[UIImage imageWithCGImage:[result aspectRatioThumbnail]];
         }
     //視頻
     else if ([[result valueForProperty:ALAssetPropertyType] isEqualToString:ALAssetTypeVideo]){ //UIImage *image=[UIImage imageWithCGImage:[result aspectRatioThumbnail]];
       [[WHViewController defaultAssetsLibrary] assetForURL:[result valueForProperty:ALAssetPropertyAssetURL] resultBlock:^(ALAsset *asset) {
                //寫入沙盒
                [self handleWrittenFile:asset];
            } failureBlock:^(NSError *error) {
                //
            }];
} }];

 

//文件寫入方法
-(void)handleWrittenFile:(ALAsset*) videoAsset
{
    NSString *DocRoot = [(NSArray*)NSSearchPathForDirectoriesInDomains(NSDocumentDirectory,NSUserDomainMask,YES) objectAtIndex:0];
    NSString *tempFile = [NSString stringWithFormat:@"%@/VideoFileName.mov",DocRoot];
    ALAssetRepresentation *rep = [videoAsset defaultRepresentation];
    NSUInteger size = [rep size];
    const int bufferSize = 65636;
    NSLog(@"written to : %@", tempFile);
    FILE *f = fopen([tempFile cStringUsingEncoding:1], "wb+");
    if (f==NULL) {
        return;
    }
    Byte *buffer =(Byte*)malloc(bufferSize);
    NSInteger read =0, offset = 0;
    NSError *error;
    if (size != 0) {
        do {
            read = [rep getBytes:buffer
                      fromOffset:offset
                          length:bufferSize
                           error:&error];
            fwrite(buffer, sizeof(char), read, f);
            offset += read;
            NSLog(@"read : %ld   total : %ld",read, offset);
        } while (read != 0);
    }
    fclose(f);
    free(buffer);
}

 

 

 

 


免責聲明!

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



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