1

I tried to fetch all images from album. It fetches all images with their URL's and image data, but it does not fetch images directly from given URL path, So I need to download images in Document Directory and then get path. So it's taking too much time. I use below code. I want fetch images like iPhone photos library fetches.

Please find error.

    func fatchImagesfromAlbum() {

        DispatchQueue.global(qos: .background).async {
        self.photoAssets = self.fetchResult as! PHFetchResult<AnyObject>

        let fetchOptions = PHFetchOptions()
        fetchOptions.predicate = NSPredicate(format: "mediaType = %d", PHAssetMediaType.image.rawValue)


        self.photoAssets = PHAsset.fetchAssets(in: self.assetCollection, options: fetchOptions) as! PHFetchResult<AnyObject>

        for i in 0..<self.photoAssets.count{
            autoreleasepool {

                let asset = self.photoAssets.object(at: i)

                let imageSize = CGSize(width: asset.pixelWidth,
                                       height: asset.pixelHeight)

                let options = PHImageRequestOptions()
                options.deliveryMode = .fastFormat
                options.isSynchronous = true
                options.isNetworkAccessAllowed = true


                self.imageManager.requestImage(for: asset as! PHAsset, targetSize: imageSize, contentMode: .aspectFill, options: options, resultHandler: { (image, info) -> Void in

                    if image != nil {
                    let image1 = image as! UIImage
                    let imageUrl          = info!["PHImageFileURLKey"] as? NSURL
                    let imageName         = imageUrl?.lastPathComponent
                    let urlString: String = imageUrl!.path!
                    let theFileName = (urlString as NSString).lastPathComponent
                    self.imageName.append("\(theFileName)")
                    self.imagePath.append("\(urlString)")

                    let documentDirectory = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
                    let photoURL          = NSURL(fileURLWithPath: documentDirectory)
                    let localPath         = photoURL.appendingPathComponent(imageName!)
                    DispatchQueue.global(qos: .background).async {
                        if !FileManager.default.fileExists(atPath: localPath!.path) {
                            do {
                                try UIImageJPEGRepresentation(image1, 0.1)?.write(to: localPath!)
                                print("file saved")
                            }catch {
                                print("error saving file")
                            }
                        }
                        else {
                            print("file already exists")
                        }
                    }
                }
              })
                DispatchQueue.main.async
                    {
                        self.collectionView.reloadData()
                }
            }
        }
        self.hudHide()
    }
        PHPhotoLibrary.shared().register(self)

    if fetchResult == nil {
        let allPhotosOptions = PHFetchOptions()
        allPhotosOptions.sortDescriptors = [NSSortDescriptor(key: "creationDate", ascending: true)]
        fetchResult = PHAsset.fetchAssets(with: allPhotosOptions)
    }
       }
halfer
  • 19,824
  • 17
  • 99
  • 186
Pankaj Jangid
  • 812
  • 9
  • 18
  • 1
    Because of iOS sandboxing, you need to copy the images from the library into your app's files. This will take time and also use a lot of device storage. It is generally a better approach to use `UIImagePickerController` to allow the user to select the image(s) they want and only copy those into your app's directory – Paulw11 Sep 28 '18 at 11:54
  • Please read [Under what circumstances may I add “urgent” or other similar phrases to my question, in order to obtain faster answers?](//meta.stackoverflow.com/q/326569) - the summary is that this is not an ideal way to address volunteers, and is probably counterproductive to obtaining answers. Please refrain from adding this to your questions. – halfer Sep 28 '18 at 12:48
  • @paulw11 I have seen an app "lalalab",which is not taking time to load images into app. I need same approach as "lalalab" . please check that app https://itunes.apple.com/us/app/lalalab-photo-printing/id586420569?mt=8 I also check cocoa control third party : https://github.com/DragonCherry/AssetsPickerViewController – Pankaj Jangid Sep 28 '18 at 13:04

1 Answers1

0

I recommend simply using UIImagePickerController or if your app requires multiple image selection functionality, a third-party library like DKImagePickerController. As another user already mentioned in the comments, these will only copy the image(s) the user selected into your app's directory and save on processing time.

sarah-bee
  • 1
  • 1
  • 2
  • I am using AssetsPickerViewController-master for fetching images, but I am facing issue that when I request for image using requestImage function, it does not have urlpath with "PHImageFileURLKey" in info of an image. So how can I get imageurl ? – Pankaj Jangid Oct 01 '18 at 11:51
  • @PankajJangid get imageurl from phasset: https://stackoverflow.com/questions/44472070/how-to-get-image-url-from-phasset-is-it-possible-to-save-image-using-phasset-ur – sarah-bee Oct 01 '18 at 20:53
  • I am trying to get ImageUrl from given example, But with info Dictionary, It prints like : ([AnyHashable("PHImageResultIsPlaceholderKey"): 0, AnyHashable("PHImageResultDeliveredImageFormatKey"): 9999, AnyHashable("PHImageResultIsDegradedKey"): 0, AnyHashable("PHImageResultIsInCloudKey"): 1, AnyHashable("PHImageResultWantedImageFormatKey"): 9999]) It does not contain value with "PHImageFileURLKey". Is there any permission for that ? – Pankaj Jangid Oct 02 '18 at 05:00
  • @PankajJangid Did you add NSPhotoLibraryUsageDescription permission to your info.plist file? This is mentioned in the link I gave you. – sarah-bee Oct 02 '18 at 13:16
  • Yes, I already added NSPhotoLibraryUsageDescription permission.The problem is that it is giving image_local_url in iPad and Simulator but not in iPhone. – Pankaj Jangid Oct 02 '18 at 13:55
  • @PankajJangid The only other thing I can think of is that the photos you are trying to access are in iCloud. The PHImageResultIsInCloudKey is 1 in your example, which means the image is in iCloud and may not be downloaded to the device and does not have aPHImageFileURLKey. But I don't know for sure. Sorry. – sarah-bee Oct 02 '18 at 13:58