Search code examples
iosswiftuiscrollviewuiimageviewuipagecontrol

Incorrect image written to iOS photo album


I am using UIImageWriteToSavedPhotosAlbum() to save images to the photo album of the device.

I have my images in an array and they are displayed on a PageControl.

A download icon on the navigationBar saves the image to Photos.

I am able to save the image to Photos but the image saved is incorrect i.e. the image at the particular index is not saved. This is how I am adding all images to the page-control....

func scrollImagesWhileViewChange() {

    for i in arrayOfURLImages {

    self.pageControl.size(forNumberOfPages: arrayOfURLImages.count)
        let scrollViewWidth:CGFloat = self.scrollView.frame.width
        let scrollViewHeight:CGFloat = self.scrollView.frame.height
        let index = arrayOfURLImages.index(of: i)
        let imageA = UIImageView(frame: CGRect(x: CGFloat(index!) * scrollViewWidth, y:0,width:scrollViewWidth, height:scrollViewHeight))
        imageA.image = i
        self.scrollView.addSubview(imageA)
        self.imageToDownload = imageA
        self.scrollView.contentSize = CGSize(width:self.scrollView.frame.width * CGFloat(arrayOfURLImages.count), height:self.scrollView.frame.height)
        self.scrollView.delegate = self
        self.pageControl.numberOfPages = arrayOfURLImages.count
        self.pageControl.currentPage = 0

}
}

In the section self.imageToDownload = imageA , I am assigning the image to a UIImageView variable. And this is how I am saving to 'Photos'..

UIImageWriteToSavedPhotosAlbum(self.imageToDownload.image!, self, #selector(MyViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)

Here the first parameter should get the correct index. But I am not able to figure out how...


Solution

  • When you click download button you need to figure out the current index of page control and then on basis of current index fetch right image from arrayOfURLImages and then save to photo album.

    Try this-

    UIImageWriteToSavedPhotosAlbum(arrayOfURLImages[self.pageControl.currentPage], self, #selector(MyViewController.image(_:didFinishSavingWithError:contextInfo:)), nil)