iosiphoneswift3image-galleryphfetchoptions

get thumbnail images in list and full size image when click on the item of list


So I am using below code to fetch all the images from library which is working fine :

func grabPhotos(){

   let imgManager = PHImageManager.default()
   let requestOptions = PHImageRequestOptions()
   requestOptions.isSynchronous = true
   requestOptions.deliveryMode = .highQualityFormat
   let fetchOptions = PHFetchOptions()
   fetchOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
   if let fetchResults : PHFetchResult = PHAsset.fetchAssets(with: .image, options: fetchOptions){

      if fetchResults.count>0{

       for i in 0..<fetchResults.count{

         imgManager.requestImage(for: fetchResults.object(at: i), targetSize: CGSize(width:100, height: 100), contentMode: .aspectFill, options: requestOptions, resultHandler: {

         image, error in
        self.Galleryimages.append(image!)

        print("array count is ",self.Galleryimages.count)
        self.photoCollectionview.reloadData()
      })
      }

    }
  }
}

I am showing all the images in my UICollectionView, but I didn't find any way to get original image whenever clicking on any thumbnail image. I want to fetch the original image (full size image) when user clicks on any thumbnail image which is populated in UICollectionView.

Thank you.


Solution

  • To load thumbnail image.

    Got the solution after doing too much stuff, may be it can help to others. Below are the steps to do this.

    Step 1 : Declare object of PHFetchResult

    var Galleryimages: PHFetchResult<PHAsset>!
    

    Step 2 : Fetch results from gallery using below code:

    func grabPhotos(){
    
    Galleryimages = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil)
    

    }

    Step 3 : Show the thumbnail images in your UI (collectionview/Tableview) using below code :

    let imageview = cell.viewWithTag(1) as! UIImageView
    
    PHImageManager.default().requestImage(for: (Galleryimages?[indexPath.row])!, targetSize: CGSize(width: 200, height: 200), contentMode: .aspectFill, options: nil) { (image: UIImage?, info: [AnyHashable: Any]?) -> Void in
      imageview.image = image
    }
    

    Step 4 : And finally get the full size image using below code.

    let options = PHImageRequestOptions()
    options.deliveryMode = .highQualityFormat
    options.resizeMode = .exact
    
    PHImageManager.default().requestImage(for: (Galleryimages[indexPath.row]), targetSize: PHImageManagerMaximumSize, contentMode: .aspectFill, options: options) { (image: UIImage?, info: [AnyHashable: Any]?) -> Void in
      if let image = image {
        //Use this originan image
      }
    }