async Task <IList <MediaAsset> > LoadMediaAsync()
        {
            IList <MediaAsset> assets = new List <MediaAsset>();
            var imageManager          = new PHCachingImageManager();
            var hasPermission         = await RequestPermissionAsync();

            if (hasPermission)
            {
                await Task.Run(async() =>
                {
                    var thumbnailRequestOptions                  = new PHImageRequestOptions();
                    thumbnailRequestOptions.ResizeMode           = PHImageRequestOptionsResizeMode.Fast;
                    thumbnailRequestOptions.DeliveryMode         = PHImageRequestOptionsDeliveryMode.FastFormat;
                    thumbnailRequestOptions.NetworkAccessAllowed = true;
                    thumbnailRequestOptions.Synchronous          = true;

                    var requestOptions                  = new PHImageRequestOptions();
                    requestOptions.ResizeMode           = PHImageRequestOptionsResizeMode.Exact;
                    requestOptions.DeliveryMode         = PHImageRequestOptionsDeliveryMode.HighQualityFormat;
                    requestOptions.NetworkAccessAllowed = true;
                    requestOptions.Synchronous          = true;

                    var fetchOptions             = new PHFetchOptions();
                    fetchOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) };
                    fetchOptions.Predicate       = NSPredicate.FromFormat($"mediaType == {(int)PHAssetMediaType.Image} || mediaType == {(int)PHAssetMediaType.Video}");
                    var fetchResults             = PHAsset.FetchAssets(fetchOptions);
                    var tmpPath       = Path.GetTempPath();
                    var allAssets     = fetchResults.Select(p => p as PHAsset).ToArray();
                    var thumbnailSize = new CGSize(300.0f, 300.0f);

                    imageManager.StartCaching(allAssets, thumbnailSize, PHImageContentMode.AspectFit, thumbnailRequestOptions);
                    imageManager.StartCaching(allAssets, PHImageManager.MaximumSize, PHImageContentMode.AspectFit, requestOptions);


                    foreach (var result in fetchResults)
                    {
                        var phAsset = (result as PHAsset);
                        var name    = PHAssetResource.GetAssetResources(phAsset)?.FirstOrDefault()?.OriginalFilename;
                        var asset   = new MediaAsset()
                        {
                            Id   = phAsset.LocalIdentifier,
                            Name = name,
                            Type = phAsset.MediaType == PHAssetMediaType.Image ? MediaAssetType.Image : MediaAssetType.Video,
                        };

                        imageManager.RequestImageForAsset(phAsset, thumbnailSize, PHImageContentMode.AspectFit, thumbnailRequestOptions, (image, info) =>
                        {
                            if (image != null)
                            {
                                NSData imageData = null;
                                if (image.CGImage.RenderingIntent == CGColorRenderingIntent.Default)
                                {
                                    imageData = image.AsJPEG(0.8f);
                                }
                                else
                                {
                                    imageData = image.AsPNG();
                                }

                                if (imageData != null)
                                {
                                    var fileName  = Path.Combine(tmpPath, $"tmp_thumbnail_{Path.GetFileNameWithoutExtension(name)}.jpg");
                                    NSError error = null;
                                    imageData.Save(fileName, true, out error);
                                    if (error == null)
                                    {
                                        asset.PreviewPath = fileName;
                                    }
                                }
                            }
                        });
                        switch (phAsset.MediaType)
                        {
                        case PHAssetMediaType.Image:

                            imageManager.RequestImageForAsset(phAsset, PHImageManager.MaximumSize, PHImageContentMode.AspectFit, requestOptions, (image, info) =>
                            {
                                if (image != null)
                                {
                                    NSData imageData = null;
                                    if (image.CGImage.RenderingIntent == CGColorRenderingIntent.Default)
                                    {
                                        imageData = image.AsJPEG(0.8f);
                                    }
                                    else
                                    {
                                        imageData = image.AsPNG();
                                    }

                                    if (imageData != null)
                                    {
                                        var fileName  = Path.Combine(tmpPath, $"tmp_{name}");
                                        NSError error = null;
                                        imageData.Save(fileName, true, out error);
                                        if (error == null)
                                        {
                                            asset.Path = fileName;
                                        }
                                    }
                                }
                            });
                            break;

                        case PHAssetMediaType.Video:
                            var videoRequestOptions = new PHVideoRequestOptions();
                            videoRequestOptions.NetworkAccessAllowed = true;
                            var tcs = new TaskCompletionSource <bool>();
                            imageManager.RequestAvAsset(phAsset, null, (vAsset, audioMix, info) =>
                            {
                                var avAsset   = vAsset as AVUrlAsset;
                                var avData    = NSData.FromUrl(avAsset.Url);
                                NSError error = null;
                                var path      = Path.Combine(tmpPath, $"tmp_{name}");
                                avData.Save(path, true, out error);
                                if (error == null)
                                {
                                    asset.Path = path;


                                    tcs.TrySetResult(true);
                                }
                                else
                                {
                                    tcs.TrySetResult(false);
                                }
                            });
                            await tcs.Task;
                            break;
                        }

                        UIApplication.SharedApplication.InvokeOnMainThread(delegate
                        {
                            OnMediaAssetLoaded?.Invoke(this, new MediaEventArgs(asset));
                        });
                        assets.Add(asset);

                        if (requestStop)
                        {
                            break;
                        }
                    }
                });

                imageManager.StopCaching();
            }

            return(assets);
        }
Esempio n. 2
0
 private void ResetCachedAssets()
 {
     _imageManager.StopCaching();
     _previousPreheatRect = CGRect.Empty;
 }
Esempio n. 3
0
        public Task <IEnumerable <MediaAsset> > Query(MediaTypes mediaTypes, DateTimeOffset date)
        {
            var tcs = new TaskCompletionSource <IEnumerable <MediaAsset> >();

            Task.Run(() =>
            {
                var filter = "creationDate >= %@ && " + GetFilter(mediaTypes);

                var fetchOptions = new PHFetchOptions
                {
                    IncludeHiddenAssets   = false,
                    IncludeAllBurstAssets = false,
                    Predicate             = NSPredicate.FromFormat(filter, (NSDate)date.LocalDateTime),
                    SortDescriptors       = new [] {
                        new NSSortDescriptor("creationDate", false)
                    }
                };

                var fetchAssets = PHAsset
                                  .FetchAssets(fetchOptions)
                                  .OfType <PHAsset>()
                                  .ToArray();

                var options = new PHAssetResourceRequestOptions
                {
                    NetworkAccessAllowed = false
                };


                var imageCache = new PHCachingImageManager();
                imageCache.StartCaching(
                    fetchAssets,
                    PHImageManager.MaximumSize,
                    PHImageContentMode.Default,
                    new PHImageRequestOptions
                {
                    NetworkAccessAllowed = false
                }
                    );

                var assets = new List <MediaAsset>(fetchAssets.Count());
                foreach (var asset in fetchAssets)
                {
                    //result.MediaType
                    //result.Hidden
                    //result.Duration
                    //result.LocalIdentifier
                    //result.Location;
                    //result.ModificationDate
                    //result.PixelHeight;
                    //result.PixelWidth;
                    //result.CreationDate

                    switch (asset.MediaType)
                    {
                    case PHAssetMediaType.Image:
                        imageCache.RequestImageData(
                            asset,
                            new PHImageRequestOptions
                        {
                        },
                            (data, fn, orientation, dict) => { }
                            );
                        break;

                    case PHAssetMediaType.Video:
                        imageCache.RequestAvAsset(
                            asset,
                            new PHVideoRequestOptions
                        {
                            NetworkAccessAllowed = false,
                            DeliveryMode         = PHVideoRequestOptionsDeliveryMode.HighQualityFormat
                        },
                            (ass, mix, dict) => { }
                            );
                        break;

                    case PHAssetMediaType.Audio:
                        break;
                    }
                }
                imageCache.StopCaching();
                tcs.SetResult(assets);
            });
            return(tcs.Task);
        }