Get ImageSource from iOS Photo Library

Hi everyone,

I'm wanting to get ImageSource from iOS Photo Library to display photos in Xamarin.Forms. I'm using PhotoKit to iterate over all photos

    public List<Picture> GetLocalImages()
            {
                List<Picture> pictures = new List<Picture>();

                var fetchOptions = new PHFetchOptions();
                fetchOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("modificationDate", false) };
                PHFetchResult fetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, fetchOptions);

                foreach (var item in fetchResults)
                {
                    var phasset = (PHAsset)item;
                    var lowResolution = phasset.PixelWidth < 1200 || phasset.PixelHeight < 1200;

                    PHImageManager.DefaultManager.RequestImageData(phasset, null, (data, dataUti, orientation, info) => 
                    {
                        var pic = new Picture(ImageSource.FromStream(data.AsStream), DateTime.Now, lowResolution);
                        pictures.Add(pic);
                    });
                }

                return pictures;
            }

But when the image is shown, I'm not seeing it.

Could you help me?

Thanks,

Posts

  • jdprigionijdprigioni Member ✭✭

    I've found the solution

    public List<Picture> GetLocalImages()
            {
                List<Picture> pictures = new List<Picture>();
    
                var fetchOptions = new PHFetchOptions();
                fetchOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("modificationDate", false) };
                PHFetchResult fetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, fetchOptions);
    
                foreach (var item in fetchResults)
                {
                    var phasset = (PHAsset)item;
                    var lowResolution = phasset.PixelWidth < 1200 || phasset.PixelHeight < 1200;
                    var size = new CoreGraphics.CGSize(phasset.PixelWidth, phasset.PixelHeight);
    
                    PHImageManager.DefaultManager.RequestImageForAsset(phasset, size, PHImageContentMode.Default, null, (result, info) => 
                    {
                        NSData data = result.AsJPEG(1);
                        var pic = new Picture(ImageSource.FromStream(data.AsStream), DateTime.Now, lowResolution);
                        pictures.Add(pic);
                    });
                }
    
                return pictures;
            }
    
Sign In or Register to comment.