码迷,mamicode.com
首页 > 移动开发 > 详细

iOS中相册-用一个tableView区分照片和video

时间:2015-01-07 12:21:27      阅读:238      评论:0      收藏:0      [点我收藏+]

标签:

 

  1. <span style="font-size:18px;">  
  2. #import "ViewController.h"  
  3.   
  4. @interface ViewController ()  
  5.   
  6. @property(nonatomic,strong)UITableView *tableView;  
  7. @property(nonatomic,strong)NSMutableArray *assets;// 照片数组  
  8. @property(nonatomic,strong)NSMutableArray *videoArr;// 视频数组  
  9. @property(nonatomic,strong)ALAssetsLibrary *library;  
  10.   
  11. @end  
  12.   
  13. @implementation ViewController  
  14.   
  15. - (void)viewDidLoad  
  16. {  
  17.     [super viewDidLoad];  
  18.     self.view.backgroundColor = [UIColor blackColor];  
  19.       
  20.     NSLog(@"%ld", [ALAssetsLibrary authorizationStatus]);  
  21.       
  22.     self.assets = [[NSMutableArray alloc]initWithCapacity:0];  
  23.     self.videoArr = [[NSMutableArray alloc]initWithCapacity:0];  
  24.       
  25.     self.tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 50, 320, 416) style:UITableViewStyleGrouped];  
  26.     self.tableView.delegate = self;  
  27.     self.tableView.dataSource = self;  
  28.     [self.view addSubview:self.tableView];  
  29.       
  30.     UIView *view = [[UIView alloc]initWithFrame:CGRectMake(0, self.tableView.frame.size.height+70, 320, 80)];  
  31.     view.backgroundColor = [UIColor yellowColor];  
  32.     UIButton *btn1 = [UIButton buttonWithType:UIButtonTypeRoundedRect];  
  33.     btn1.frame = CGRectMake(10, 10, 100, 50);  
  34.     [btn1 setTitle:@"测试添加相册" forState:UIControlStateNormal];  
  35.     [btn1 addTarget:self action:@selector(addGroud) forControlEvents:UIControlEventTouchUpInside];  
  36.     [view addSubview:btn1];  
  37.     [self.view addSubview:view];  
  38.       
  39.     self.library = [[ALAssetsLibrary alloc] init];  
  40.       
  41.     void (^assetEnumerator)(ALAsset *, NSUInteger, BOOLBOOL *) = ^(ALAsset *result, NSUInteger index, BOOLBOOL *stop) {  
  42.         if(result != NULL) {  
  43.               
  44.             if ([result valueForProperty:ALAssetPropertyType] == ALAssetTypeVideo) {  
  45.                 [self.videoArr addObject:result];  
  46.             }else if([result valueForProperty:ALAssetPropertyType] == ALAssetTypePhoto){  
  47.                 [self.assets addObject:result];  
  48.             }  
  49.               
  50.         }  
  51.     };  
  52.       
  53.     //便利相册  
  54.     void (^assetGroupEnumerator)(ALAssetsGroup *, BOOLBOOL *) =  ^(ALAssetsGroup *group, BOOLBOOL *stop) {  
  55.   
  56.         if(group != nil) {  
  57.             [group enumerateAssetsUsingBlock:assetEnumerator];  
  58.         }  
  59.           
  60.         [self.tableView reloadData];  
  61.     };  
  62.       
  63. //    //便利所有相册  
  64.     [self.library enumerateGroupsWithTypes:ALAssetsGroupAll  
  65.                            usingBlock:assetGroupEnumerator  
  66.                          failureBlock: ^(NSError *error) {  
  67.                              NSLog(@"便利所有相册");  
  68.                                
  69.                          }];  
  70.       
  71.       
  72.     [self.tableView reloadData];  
  73.       
  74.    
  75. }  
  76.   
  77. - (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{  
  78.     return 2;  
  79. }  
  80.   
  81. - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {  
  82.       
  83.     if (section == 0) {  
  84.           
  85.         if ([self.assets count]>5) {  
  86.             return 5;  
  87.         }else{  
  88.             return [self.assets count];  
  89.         }  
  90.           
  91.     }else{  
  92.           
  93.         if ([self.videoArr count]>5) {  
  94.             return 5;  
  95.         }else{  
  96.             return [self.videoArr count];  
  97.         }  
  98.           
  99.     }  
  100.       
  101. }  
  102.   
  103. - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {  
  104.     static NSString *CellIdentifier = @"Cell";  
  105.       
  106.     UITableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:CellIdentifier];  
  107.     if (cell == nil) {  
  108.         cell = [[UITableViewCell alloc] initWithStyle:UITableViewCellStyleDefault reuseIdentifier:CellIdentifier];  
  109.     }  
  110.       
  111.       
  112.     if (indexPath.section == 0) {  
  113.         ALAsset *asset = [self.assets objectAtIndex:indexPath.row];  
  114.           
  115.         struct CGImage *imagecg = asset.thumbnail;  
  116.         UIImage *image = [UIImage imageWithCGImage:imagecg];  
  117.           
  118.         [cell.imageView setImage:image];  
  119.         [cell.textLabel setText:[NSString stringWithFormat:@"Photo %d", indexPath.row+1]];  
  120.     }else if (indexPath.section == 1){  
  121.           
  122.         ALAsset *asset = [self.videoArr objectAtIndex:indexPath.row];  
  123.           
  124.         struct CGImage *imagecg = asset.thumbnail;  
  125.         UIImage *image = [UIImage imageWithCGImage:imagecg];  
  126.           
  127.         [cell.imageView setImage:image];  
  128.         [cell.textLabel setText:[NSString stringWithFormat:@"video %d", indexPath.row+1]];  
  129.   
  130.     }  
  131.   
  132.     return cell;  
  133. }  
  134. </span>  




添加一个图片到默认相册

  1. <span style="font-size:18px;">  
  2. //添加图片到相册  
  3.     NSString *path = [[NSBundle mainBundle] pathForResource:@"123" ofType:@"png"];  
  4.     NSURL *urll = [NSURL fileURLWithPath:path];  
  5.     NSData *data = [NSData dataWithContentsOfURL:urll];  
  6.     [_library writeImageDataToSavedPhotosAlbum:data metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {  
  7.           
  8.     }];  
  9.       
  10.     //保存图片到系统默认的相册中,使用nsdata的形式,并返回照片的url地址  
  11.     [_library writeImageDataToSavedPhotosAlbum:nil metadata:nil completionBlock:^(NSURL *assetURL, NSError *error) {  
  12.       
  13.     }];</span>  




创建一个相册

  1. <span style="font-size:18px;">- (void)addGroud{  
  2.     [self.library addAssetsGroupAlbumWithName:@"测试添加相册" resultBlock:^(ALAssetsGroup *group) {  
  3.         NSLog(@"addAssetsGroupAlbumWithName");  
  4.         //        //查看相册的名字  
  5.         NSLog(@"ALAssetsGroupPropertyName:%@",[group valueForProperty:ALAssetsGroupPropertyName]);  
  6.         //        //查看相册的类型  
  7.         NSLog(@"ALAssetsGroupPropertyType:%@",[group valueForProperty:ALAssetsGroupPropertyType]);  
  8.         //        //查看相册的存储id  
  9.         NSLog(@"ALAssetsGroupPropertyPersistentID:%@",[group valueForProperty:ALAssetsGroupPropertyPersistentID]);  
  10.         //        //查看相册存储的位置地址  
  11.         NSLog(@"ALAssetsGroupPropertyURL:%@",[group valueForProperty:ALAssetsGroupPropertyURL]);  
  12.         NSURL *groupURL = [group valueForProperty:ALAssetsGroupPropertyURL];  
  13.           
  14.     } failureBlock:^(NSError *error) {  
  15.         NSLog(@"ERR : %@",error);  
  16.     }];  
  17.   
  18. }  
  19. </span>  



保存video到相册

  1. <span style="font-size:18px;">  
  2.   
  3. //保存video到相册  
  4. - (void)saveVideo:(NSString *)videoPath toAlbum:(NSString *)albumName withCompletionBlock:(SaveImageCompletion)completionBlock  
  5. {  
  6.     [self writeVideoAtPathToSavedPhotosAlbum:[NSURL fileURLWithPath:videoPath]  
  7.                              completionBlock:^(NSURL *assetURL, NSError *error) {  
  8.                                  if (error!=nil) {  
  9.                                      completionBlock(error);  
  10.                                      return;  
  11.                                  }  
  12.                                    
  13.                                  //add the asset to the custom photo album  
  14.                                  [self addAssetURL: assetURL  
  15.                                            toAlbum:albumName  
  16.                                withCompletionBlock:completionBlock];  
  17.                              }];  
  18. }  
  19.   
  20.   
  21. -(void)addAssetURL:(NSURL*)assetURL toAlbum:(NSString*)albumName withCompletionBlock:(SaveImageCompletion)completionBlock  
  22. {  
  23.     __block BOOL albumWasFound = NO;  
  24.       
  25.     //search all photo albums in the library  
  26.     //遍历相册  
  27.     [self enumerateGroupsWithTypes:ALAssetsGroupAlbum   
  28.                         usingBlock:^(ALAssetsGroup *group, BOOLBOOL *stop) {  
  29.   
  30.                             //compare the names of the albums  
  31.                             if ([albumName compare: [group valueForProperty:ALAssetsGroupPropertyName]]==NSOrderedSame) {  
  32.                                   
  33.                                 //target album is found  
  34.                                 albumWasFound = YES;  
  35.                                   
  36.                                 //get a hold of the photo‘s asset instance  
  37.                                 //通过url得到asset  
  38.                                 [self assetForURL: assetURL   
  39.                                       resultBlock:^(ALAsset *asset) {  
  40.                                                     
  41.                                           //add photo to the target album  
  42.                                           [group addAsset: asset];  
  43.                                             
  44.                                           //run the completion block  
  45.                                           completionBlock(nil);  
  46.                                             
  47.                                       } failureBlock: completionBlock];  
  48.   
  49.                                 //album was found, bail out of the method  
  50.                                 return;  
  51.                             }  
  52.                               
  53.                             //如果没有 创建相册加入asset  
  54.                             if (group==nil && albumWasFound==NO) {  
  55.                                 //photo albums are over, target album does not exist, thus create it  
  56.                                   
  57.                                 ALAssetsLibrary* weakSelf = self;  
  58.   
  59.                                 //create new assets album  
  60.                                 [self addAssetsGroupAlbumWithName:albumName   
  61.                                                       resultBlock:^(ALAssetsGroup *group) {  
  62.                                                                     
  63.                                                           //get the photo‘s instance  
  64.                                                           [weakSelf assetForURL: assetURL   
  65.                                                                         resultBlock:^(ALAsset *asset) {  
  66.   
  67.                                                                             //add photo to the newly created album  
  68.                                                                             [group addAsset: asset];  
  69.                                                                               
  70.                                                                             //call the completion block  
  71.                                                                             completionBlock(nil);  
  72.   
  73.                                                                         } failureBlock: completionBlock];  
  74.                                                             
  75.                                                       } failureBlock: completionBlock];  
  76.   
  77.                                 //should be the last iteration anyway, but just in case  
  78.                                 return;  
  79.                             }  
  80.                               
  81.                         } failureBlock: completionBlock];  
  82.       
  83. }  
  84. </span>  




保存png到指定相册

  1. <span style="font-size:18px;">  
  2. //保存图片到系统默认的相册中,使用cgimageref的形式,并且选择图片以什么旋转方向的形式保存,并返回照片的url地址  
  3.     /* 
  4.      typedef enum { 
  5.      ALAssetOrientationUp,            // default orientation 
  6.      ALAssetOrientationDown,          // 180 deg rotation 
  7.      ALAssetOrientationLeft,          // 90 deg CCW 
  8.      ALAssetOrientationRight,         // 90 deg CW 
  9.      ALAssetOrientationUpMirrored,    // as above but image mirrored along other axis. horizontal flip 
  10.      ALAssetOrientationDownMirrored,  // horizontal flip 
  11.      ALAssetOrientationLeftMirrored,  // vertical flip 
  12.      ALAssetOrientationRightMirrored, // vertical flip 
  13.      } ALAssetOrientation; 
  14.      */  
  15.     UIImage* image = [UIImage imageNamed:@"123"];  
  16.     [_library writeImageToSavedPhotosAlbum:[image CGImage] orientation:ALAssetOrientationLeft completionBlock:^(NSURL *assetURL, NSError *error) {  
  17.         NSLog(@"save image:%@",assetURL);  
  18.         //通过ALAssetsLibrary迭代取出所有相册  
  19.         [_library enumerateGroupsWithTypes:ALAssetsGroupAll usingBlock:^(ALAssetsGroup *group, BOOLBOOL *stop) {  
  20.             NSString* groupname = [group valueForProperty:ALAssetsGroupPropertyName];  
  21.             //如果相册的名称是test的时候,对其进行操作  
  22.             if ([groupname isEqualToString:@"测试添加相册"]) {  
  23.                 //设置相册组的筛选条件,ALAssetsFilter类表示筛选条件,allPhotos代表相册只包含相片,allVideos代表只包含视频,allAssets代表包含所有资源  
  24.                 [group setAssetsFilter:[ALAssetsFilter allPhotos]];  
  25.                 //通过刚保存的照片的url,把保存到默认相册的照片也保存到test相册中  
  26.                 [_library assetForURL:assetURL resultBlock:^(ALAsset *asset) {  
  27.                     //添加资源到指定的相册  
  28.                     [group addAsset:asset];  
  29.                     //获取相册中一共的资源数量  
  30.                     int count = [group numberOfAssets];  
  31.                     NSLog(@"count:%d",count);  
  32.                     dispatch_queue_t main = dispatch_get_main_queue();  
  33.                     dispatch_async(main, ^{  
  34.                         //获取相册的封面图片  
  35.                         CGImageRef poster = [group posterImage];  
  36.                           
  37.                     });  
  38.                     //NSString *const ALAssetsGroupPropertyName;  
  39.                     //NSString *const ALAssetsGroupPropertyType;  
  40.                     //NSString *const ALAssetsGroupPropertyPersistentID;  
  41.                     //NSString *const ALAssetsGroupPropertyURL;  
  42.                     //查看相册的名字  
  43.                     NSLog(@"ALAssetsGroupPropertyName:%@",[group valueForProperty:ALAssetsGroupPropertyName]);  
  44.                     //查看相册的类型  
  45.                     NSLog(@"ALAssetsGroupPropertyType:%@",[group valueForProperty:ALAssetsGroupPropertyType]);  
  46.                     //查看相册的存储id  
  47.                     NSLog(@"ALAssetsGroupPropertyPersistentID:%@",[group valueForProperty:ALAssetsGroupPropertyPersistentID]);  
  48.                     //查看相册存储的位置地址  
  49.                     NSLog(@"ALAssetsGroupPropertyURL:%@",[group valueForProperty:ALAssetsGroupPropertyURL]);  
  50.                     //按遍历顺序获取指定索引的资源,遍历顺序可以是先序或倒序  
  51.                     /* 
  52.                      enum { 
  53.                      NSEnumerationConcurrent = (1UL << 0), 
  54.                      NSEnumerationReverse = (1UL << 1), 
  55.                      }; 
  56.                      typedef NSUInteger NSEnumerationOptions; 
  57.                      */  
  58.                     [group enumerateAssetsAtIndexes:[NSIndexSet indexSetWithIndex:0] options:NSEnumerationConcurrent usingBlock:^(ALAsset *result, NSUInteger index, BOOLBOOL *stop) {  
  59.                           
  60.                     }];  
  61.                     //按顺便遍历获取相册中所有的资源,index代表资源的索引,stop赋值为false时,会停止遍历  
  62.                     [group enumerateAssetsUsingBlock:^(ALAsset *result, NSUInteger index, BOOLBOOL *stop) {  
  63.                           
  64.                     }];  
  65.                     //按顺便遍历获取相册中所有的资源,遍历顺序可以是先序或倒序,index代表资源的索引,stop赋值为false时,会停止遍历  
  66.                     [group enumerateAssetsWithOptions:NSEnumerationReverse usingBlock:^(ALAsset *result, NSUInteger index, BOOLBOOL *stop) {  
  67.                           
  68.                     }];  
  69.                       
  70.                 } failureBlock:^(NSError *error) {  
  71.                       
  72.                 }];  
  73.             }  
  74.         } failureBlock:^(NSError *error) {  
  75.               
  76.         }];  
  77.     }];  
  78. </span>  


参考文章:http://blog.csdn.net/kingsley_cxz/article/category/1466803

iOS中相册-用一个tableView区分照片和video

标签:

原文地址:http://www.cnblogs.com/allanliu/p/4207841.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!