Forum Xamarin.iOS
We are excited to announce that the Xamarin Forums are moving to the new Microsoft Q&A experience. Q&A is the home for technical questions and answers at across all products at Microsoft now including Xamarin!

We encourage you to head over to Microsoft Q&A for .NET for posting new questions and get involved today.

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)
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)
            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.




  • trishelwoodtrishelwood USMember ✭✭

    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.