2016年5月6日 星期五

讀取相簿名稱


上次試過讀取相機菲林最後的相片,今次則是讀取相簿名稱。

原本很懶,只想快速從源代碼中找到讀取相簿名稱的方法。花了一段時間,仍然無法成功。只好乖乖地細看文件說明。一會兒,能成功讀取相簿名稱及其相片。有時是急不來。錯,是由於 FetchResult 有三種內容,錯配便會出錯。得理解後才知道甚麼時候該做甚麼。 首先,我想在應用程式內顯示「所有相片」及其他預設相簿:
   PHFetchOptions *allPhotosOptions = [[PHFetchOptions alloc] init];
   allPhotosOptions.sortDescriptors = @[[NSSortDescriptor sortDescriptorWithKey:@"creationDate" ascending:YES]];
   PHFetchResult *allPhotos = [PHAsset fetchAssetsWithOptions:allPhotosOptions];
   
   PHFetchResult *smartAlbums = [PHAssetCollection fetchAssetCollectionsWithType:PHAssetCollectionTypeSmartAlbum subtype:PHAssetCollectionSubtypeAlbumRegular options:nil];
   
   _sectionFetchResultArray = @[allPhotos, smartAlbums];
之後,我用 UITableView 來顯示,所以在構成 UITableViewCell 時要讀取相簿名稱:
   
   //  Setup album name
   if (indexPath.section == 0)  {
      string = NSLocalizedString(@"SELECTPHOTOVIEW_ALLPHOTOS", nil);
   }  else  {

      PHFetchResult *assetCollectionResult = _sectionFetchResultArray[indexPath.section];
      PHCollection *collection = assetCollectionResult[indexPath.row];
      string = collection.localizedTitle;
   }
   label = (UILabel *)[cell viewWithTag:SELECTPHOTOVIEW_TAG_ALBUMNAME];
   [label setText:string];
及相片:
   //  Setup thumbnail image
   imageView = (UIImageView *)[cell viewWithTag:SELECTPHOTOVIEW_TAG_THUMBNAIL];
   width = imageView.frame.size.width;
   height = imageView.frame.size.height;

   PHFetchResult *assetResult = _sectionFetchResultArray[indexPath.section];
   if (indexPath.section == 0)  {

      //  All photos
      count = [assetResult count];
      if (count == 0)  {

         //  If no photo was found, use thumbnail
         image = [BZImage imageNamed:SELECTPHOTOVIEW_FILE_THUMBNAIL];
         [imageView setImage:image];
      }  else  {

         //  Have photos, get the latest one
         PHAsset *asset = [assetResult lastObject];
         [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(width, height) contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage *result, NSDictionary *info)  {
            [imageView setImage:result];
         }];
      }
   }  else  {

      //  Smart albums
      PHAssetCollection *collection = [assetResult objectAtIndex:indexPath.row];
      PHFetchResult *result = [PHAsset fetchAssetsInAssetCollection:collection options:nil];

      count = [result count];
      if (count == 0)  {

         //  If no photo was found, use thumbnail
         image = [BZImage imageNamed:SELECTPHOTOVIEW_FILE_THUMBNAIL];
         [imageView setImage:image];
      }  else  {
         
         //  Have photos, get the latest one
         PHAsset *asset = [result lastObject];
         [[PHImageManager defaultManager] requestImageForAsset:asset targetSize:CGSizeMake(width, height) contentMode:PHImageContentModeAspectFit options:nil resultHandler:^(UIImage *result, NSDictionary *info)  {
            [imageView setImage:result];
         }];
      }
   }

沒有留言: