Retrieving Assets from the Assets Library(不用内置GUI组件,检索手机中的相片/视频资源)

1.导入库,实现的协议   

   #import<MobileCoreServices/MobileCoreServices.h>

       #import <AssetsLibrary/AssetsLibrary.h>

   protocol: <UIImagePickerControllerDelegate,UINavigationControllerDelegate>

  使用方法:

- (void)enumerateGroupsWithTypes:(ALAssetsGroupType)types usingBlock:(ALAssetsLibraryGroupsEnumerationResultsBlock)enumerationBlock failureBlock:(ALAssetsLibraryAccessFailureBlock)failureBlock


e.g.(一)

- (void)actionRetrieve{

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

    [assetsLibrary   enumerateGroupsWithTypes:ALAssetsGroupAll

         usingBlock:^(ALAssetsGroup *group, BOOL *stop) {

             [group  enumerateAssetsUsingBlock:^(ALAsset *result,

                                            NSUInteger index,

                                            BOOL *stop){             

             /* Get the asset type */

             NSString *assetType = [result  valueForProperty:ALAssetPropertyType];            

             if ([assetType isEqualToString:ALAssetTypePhoto]){

                 NSLog(@"This is a photo asset");

             }             

             else if ([assetType isEqualToString:ALAssetTypeVideo]){

                 NSLog(@"This is a video asset");

             }             

             else if ([assetType isEqualToString:ALAssetTypeUnknown]){

                 NSLog(@"This is an unknown asset");

             }            

             /* Get the URLs for the asset */

             NSDictionary *assetURLs = [result valueForProperty:ALAssetPropertyURLs];            

             NSUInteger    assetCounter = 0;

             for (NSString *assetURLKey in assetURLs){

                 assetCounter++;

                 NSLog(@"Asset URL %lu = %@",(unsigned long)assetCounter,[assetURLs valueForKey:assetURLKey]);

             }            

             /* Get the asset's representation object */

             ALAssetRepresentation *assetRepresentation = [result  defaultRepresentation];             

             NSLog(@"Representation Size = %lld",[assetRepresentation size]);

             

         }];

     }

     failureBlock:^(NSError *error) {

         NSLog(@"Failed to enumerate the asset groups.");

     }];   

}


e.g.(二) 只检索第一个相片资源

/*Assets Library分解成n个group,每个group包含n个asset,每个asset包含多个properties,如URLs,等 

   groups:ALAssetsGroupAlbum,ALAssetsGroupFaces,ALAssetsGroupSavedPhotos,ALAssetsGroupAll

*/

- (void)actionRetrieve{

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

    dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);    

    dispatch_async(dispatchQueue, ^(void) {        

        [assetsLibrary

         enumerateGroupsWithTypes:ALAssetsGroupAll

         usingBlock:^(ALAssetsGroup *group, BOOL *stop1) {            

             [group enumerateAssetsUsingBlock:^(ALAsset *result,

                                                NSUInteger index,

                                                BOOL *stop2) {

                 __block BOOL foundThePhoto = NO;                             

                 /* Get the asset type */

                 NSString *assetType = [result valueForProperty:ALAssetPropertyType];                

                 if ([assetType isEqualToString:ALAssetTypePhoto]){

                     NSLog(@"This is a photo asset in group:%@",group);                  

                     foundThePhoto = YES;

                     *stop1 = YES;

                     *stop2 = YES;

                    

                     /* Get the asset's representation object */

                    ALAssetRepresentation *assetRepresentation = [result defaultRepresentation];                     

                     /*构造合适大小和方向的图*/

                     CGFloat imageScale = [assetRepresentation scale];                    

                     UIImageOrientation imageOrientation = (UIImageOrientation)[assetRepresentation orientation];

                     dispatch_async(dispatch_get_main_queue(), ^(void) {                         

                         CGImageRef imageReference =  [assetRepresentation fullResolutionImage];                        

                         /* Construct the image now */

                         UIImage  *image =[[UIImage alloc] initWithCGImage:imageReference

                                                           scale:imageScale orientation:imageOrientation];                        

                         if (image != nil){

                             UIImageView *imageView =  [[UIImageView alloc]  initWithFrame:self.view.bounds];

                             imageView.contentMode = UIViewContentModeScaleAspectFit;

                             imageView.image = image;

                             [self.view addSubview:imageView];

                         } else {

                             NSLog(@"Failed to create the image.");

                         }

                     });                     

                 }                

             }];

         }

         failureBlock:^(NSError *error) {

             NSLog(@"Failed to enumerate the asset groups.");

         }];        

    });    

}


e.g.(三)检索手机中的视频,存入自己的应用程序目录中:先将手机中的视频内容写入buffer缓存中,然后再从buffer中写入自己的应用程序指定目录中
      (以下示例只检索第一个视频 )

- (NSString *) documentFolderPath{   

    NSFileManager *fileManager = [[NSFileManager alloc] init];

    NSURL *url =[fileManager URLForDirectory:NSDocumentDirectory

                                     inDomain:NSUserDomainMask

                            appropriateForURL:nil

                                       create:NO

                                        error:nil];    

    return url.path;    

}

- (void)actionRetrieve{

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

    dispatch_queue_t dispatchQueue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0);

    dispatch_async(dispatchQueue, ^(void) {

        [assetsLibrary

         enumerateGroupsWithTypes:ALAssetsGroupAll

         usingBlock:^(ALAssetsGroup *group, BOOL *stop) {

             __block BOOL foundTheVideo = NO;

             [group enumerateAssetsUsingBlock:^(ALAsset *result,

                                                NSUInteger index,

                                                BOOL *stop) {

                 /* Get the asset type */

                 NSString *assetType = [result valueForProperty:ALAssetPropertyType];

                 if ([assetType isEqualToString:ALAssetTypeVideo]){

                     NSLog(@"This is a video asset");

                     foundTheVideo = YES;

                     *stop = YES; //停止内循环


                     /* Get the asset's representation object */

                     ALAssetRepresentation *assetRepresentation = [result  defaultRepresentation];


                     const NSUInteger BufferSize = 1024;

                     uint8_t buffer[BufferSize];

                     NSUInteger bytesRead = 0;

                     long long currentOffset = 0;

                     NSError *readingError = nil;


                     /* 构造Video的存储路径 并创建 */

                     NSString *videoPath =[[self documentFolderPath]  stringByAppendingPathComponent:@"Temp.MOV"];

                     NSFileManager *fileManager = [[NSFileManager alloc] init];

                     if ([fileManagerfileExistsAtPath:videoPath] == NO){

                         [fileManagercreateFileAtPath:videoPath

                                              contents:nil

                                            attributes:nil];

                     }

                     /* 使用fileHandle将媒体文件内容写入磁盘,即手机中*/

                     NSFileHandle *fileHandle =[NSFileHandle  fileHandleForWritingAtPath:videoPath];

                     do{

                         /* 读取完放到buffer中 */

                         bytesRead =[assetRepresentation getBytes:(uint8_t *)&buffer

                                            fromOffset:currentOffset

                                                length:BufferSize

                                                 error:&readingError];

                         /* 读取不到则停止 */

                         if (bytesRead == 0){

                             break;

                         }

                         /* 保持最新的偏移量 */

                         currentOffset += bytesRead;

                         /* 获取buffer中的内容转化为NSData */

                         NSData *readData =[[NSData alloc] initWithBytes:(const void *)buffer length:bytesRead];

                         /* 将NSData写入文件 */

                         [fileHandle  writeData:readData];                        

                     } while (bytesRead > 0);                   

                     NSLog(@"Finished reading and storing the video in the documents folder at %@",videoPath);                    

                 }               

             }];             

             if (foundTheVideo){

                 *stop = YES; //停止外循环

             }            

         } 

         failureBlock:^(NSError *error) {

             NSLog(@"Failed to enumerate the asset groups.");

         }];        

    });   

}





评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值