Search code examples
c#xamarinphphotolibrary

How to properly fetch a custom album from PHAssetCollection


I've created a custom album now I am attempting to download a video from an FTP site and move it to the custom album.

I'm using Visual Studio 2017 Xamarin C# ios 11.4.
Permissions set in Info.plist Prior to this block, I am testing to verify the user is Authorized to access the photo library.

This is my first time using PHPhotoLibrary and I can't find many C# code samples.

No error generated, just crashes at the line beginning PHFetchReult fetchResult.

UPDATED Found this in log on my iPad.

Date/Time: 2018-06-25 18:05:54 -0400 OS Version: iPhone OS 11.4.1 (Build 15G5072a) Architecture: arm64 Report Version: 26

Data Source: KPerf Lightweight PET Kernel Cache: 0xffffffe000000000 07AF39CA-659D-3636-4A4A-FE05631AA416 Reason: UIKit-runloop-AppStore: timeout 816ms

Command: AppStore Path: /Applications/AppStore.app/AppStore Identifier: com.apple.AppStore Version: 3.0 (1) Parent: launchd [1] PID: 4415

Duration: 0.80s Steps: 16 (50ms sampling interval)

Hardware model: J71AP Active cpus: 2

private PHAssetCollection FindAlbum(string title)
{
    PHAssetCollection photoAlbum = null;

    var fetchOptions = new PHFetchOptions() { Predicate = 
        NSPredicate.FromFormat(string.Format("title={0}", title)) };
    PHFetchResult fetchResult = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, options: fetchOptions); 

    if (fetchResult.firstObject != null)
    {
        photoAlbum = (PHAssetCollection)fetchResult.firstObject;
    }
    return photoAlbum;
}

Solution

  • I figured out what is going on and how to resolve it though I don't fully understand why the object doesn't return a null but instead crashes, perhaps this is a bug.

    In the end, the issue was that the Predicate wasn't being passed properly. I also paired down the search to include subtype of only RegularAlbums since I am looking specifically for a custom album.

    Hope this helps someone else in the C# world out :)

       private PHAssetCollection FindAlbum(string title)
        {
            PHAssetCollection photoAlbum = null;
            var arguments = new NSObject[] { NSObject.FromObject( title) };
            var fetchOptions = new PHFetchOptions() { Predicate = NSPredicate.FromFormat("title=%@", arguments) };
    
            PHFetchResult fetchResult = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.AlbumRegular, fetchOptions);
    
            if (fetchResult.firstObject != null)
            {
                photoAlbum = (PHAssetCollection)fetchResult.firstObject;
    
            }
            return photoAlbum;
        }