You can use the Photos framework to extract photos from CameraRoll / Photos.
Here is the Swift 3 code version.
Import framework
import Photos //Array of PHAsset type for storing photos var images = [PHAsset]()
Use this function to retrieve photos, somewhere in viewDidLoad , or in your action, wherever you select photos.
func getImages() { let assets = PHAsset.fetchAssets(with: PHAssetMediaType.image, options: nil) assets.enumerateObjects({ (object, count, stop) in
Rest is a data source and delegates to UICollectionView. See the cellForItem data source method in the "How to display an image" section.
func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int { return images.count } func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell { let cell = collectionView.dequeueReusableCell(withReuseIdentifier: "PhotoCollectionViewCell", for: indexPath) as! PhotoCollectionViewCell let asset = images[indexPath.row] let manager = PHImageManager.default() if cell.tag != 0 { manager.cancelImageRequest(PHImageRequestID(cell.tag)) } cell.tag = Int(manager.requestImage(for: asset, targetSize: CGSize(width: 120.0, height: 120.0), contentMode: .aspectFill, options: nil) { (result, _) in cell.photoImageView?.image = result }) return cell }
Adjust below delegates to suit your needs.
func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAt indexPath: IndexPath) -> CGSize { let width = self.view.frame.width * 0.32 let height = self.view.frame.height * 0.179910045 return CGSize(width: width, height: height) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumLineSpacingForSectionAt section: Int) -> CGFloat { return 2.5 } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, insetForSectionAt section: Int) -> UIEdgeInsets { return UIEdgeInsets(top: 5, left: 5, bottom: 5, right: 5) } func collectionView(_ collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, minimumInteritemSpacingForSectionAt section: Int) -> CGFloat { return 0 }
Be sure to keep the resolution of the photos ON . If you click "Do not allow", you will also need to manage authorization using PHPhotoLibrary.authorizationStatus()
You can learn more about the Photos framework.