Find a PHAsset by File Name

ChrisJohnsonChrisJohnson USMember ✭✭

I am trying to add PHAssets to albums I create in code. I have the add to album working, but I want to be able to find out if an image has already been placed into an album by the name of the image. That way I can choose to not add it if it already exists in the album. Here's my code so far.

` PHAsset FindAsset(string imageName, PHAssetCollection album)
{
try
{
PHAsset matchingAsset = null;

            var allPhotosOptions = new PHFetchOptions
            {
                SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", true) },
            };

            var allPhotos = PHAsset.FetchAssets(allPhotosOptions);

            for (int i = 0; i < allPhotos.Count() - 1; i++)
            {
                var asset = (PHAsset)allPhotos[i];
                PHImageManager.DefaultManager.RequestImageData(asset, null,(data, dataUti, orientation, info) => 
                {
                    var t = (info?[(NSString)@"PHImageFileURLKey"] as NSUrl).FilePathUrl.LastPathComponent;
                                if (t == imageName)
                    {
                        // We found it so return the PHAsset
                        matchingAsset = asset;
                    }
                });
                if (matchingAsset != null) return matchingAsset;
            }

            return null;

        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
            Console.WriteLine(ex.StackTrace);
            return null;
        }
    }`

It always returns null. I translated some Swift code to get part of this but it's not working in Xamarin. Any assistance is greatly appreciated.

Chris

Tagged:

Answers

  • trishelwoodtrishelwood USMember ✭✭

    @ChrisJohnson
    I have also same issue. Actually I want only local file path of the images. I was searching solution for it.

    Tried this line from your code
    var t = (info?[(NSString)@"PHImageFileURLKey"] as NSUrl).FilePathUrl.LastPathComponent;

    but it returns null for me too.

    One more question, could you tell me what is meaning of ? in info?[(NSString)@"PHImageFileURLKey"].
    Is this used for null check ?

    Thank you :smile:

Sign In or Register to comment.