public async Task <List <string> > GetGalleryPhotosAsync(int photoCount)
        {
            var photoAssets = new List <string>();

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

            var fetchAssetsResult = PHAsset.FetchAssets(PHAssetMediaType.Image, fetchOptions);

            var phAssetIndex = 0;
            var numPhotos    = fetchAssetsResult.Count;

            while (phAssetIndex < numPhotos && phAssetIndex < photoCount)
            {
                var phAsset = (PHAsset)fetchAssetsResult.ObjectAt(phAssetIndex);

                var filePath = await GetFilePathFromAssetAsync(phAsset);

                photoAssets.Add(filePath);

                phAssetIndex++;
            }

            return(photoAssets);
        }
Exemple #2
0
        public override void AwakeFromNib()
        {
            // Create a PHFetchResult object for each section in the table view.
            var allPhotosOptions = new PHFetchOptions();

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

            PHFetchResult allPhotos   = PHAsset.FetchAssets(allPhotosOptions);
            PHFetchResult smartAlbums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum,
                                                                                PHAssetCollectionSubtype.AlbumRegular, null);

            PHFetchResult topLevelUserCollections = PHCollection.FetchTopLevelUserCollections(null);

            // Store the PHFetchResult objects and localized titles for each section.
            sectionFetchResults = new [] {
                allPhotos, smartAlbums, topLevelUserCollections
            };

            sectionLocalizedTitles = new [] {
                string.Empty, "Smart Albums", "Albums", string.Empty
            };

            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);
        }
        private async void SetGalleryButton()
        {
            var status = await PHPhotoLibrary.RequestAuthorizationAsync();

            if (status == PHAuthorizationStatus.Authorized)
            {
                var options = new PHFetchOptions
                {
                    SortDescriptors = new[] { new NSSortDescriptor("creationDate", false) },
                    FetchLimit      = 5,
                };

                var fetchedAssets    = PHAsset.FetchAssets(PHAssetMediaType.Image, options);
                var lastGalleryPhoto = fetchedAssets.FirstOrDefault() as PHAsset;
                if (lastGalleryPhoto != null)
                {
                    var PHImageManager = new PHImageManager();
                    PHImageManager.RequestImageForAsset(lastGalleryPhoto, new CGSize(300, 300),
                                                        PHImageContentMode.AspectFill, new PHImageRequestOptions(), (img, info) =>
                    {
                        galleryButton.Image = img;
                    });
                }
                else
                {
                    galleryButton.Image = UIImage.FromBundle("ic_noavatar");
                }
            }
        }
Exemple #4
0
        private void LastTakenPhotoFunction()
        {
            if (!UIImagePickerController.IsSourceTypeAvailable(UIImagePickerControllerSourceType.PhotoLibrary))
            {
                alertView = new UIAlertView("SnagR Upload Photos APP", "Sorry, you cannot select pictures with your device",
                                            new UIAlertViewDelegate(), "OK");
                alertView.Show();
                return;
            }

            //imagePicker.SourceType = UIImagePickerControllerSourceType.PhotoLibrary;
            //ALAssetsLibrary library = new ALAssetsLibrary();
            PHFetchOptions fetchOptions = new PHFetchOptions();

            fetchOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) };
            PHFetchResult         fetchResult = PHAsset.FetchAssets(PHAssetMediaType.Image, fetchOptions);
            PHAsset               lastAsset   = (Photos.PHAsset)fetchResult.LastObject;
            PHImageRequestOptions option      = new PHImageRequestOptions();

            option.ResizeMode = PHImageRequestOptionsResizeMode.Exact;
            PHImageManager.DefaultManager.RequestImageData(lastAsset, option, (data, dataUti, orientation, info) => nsSelectedImage = data);

            //PHImageManager.DefaultManager.RequestImageForAsset(lastAsset, new CGSize(100, 100), PHImageContentMode.AspectFill, options:option,(UIImage result, NSDictionary info) => {selectedImage = result});
            selectedImage        = UIImage.LoadFromData(nsSelectedImage);
            TestImagePlace.Image = selectedImage;
            //imagePicker.AssetsLibrary

            UploadProcess();
        }
		public override void AwakeFromNib ()
		{
			// Create a PHFetchResult object for each section in the table view.
			var allPhotosOptions = new PHFetchOptions ();
			allPhotosOptions.SortDescriptors = new [] {
				new NSSortDescriptor ("creationDate", true)
			};

			PHFetchResult allPhotos = PHAsset.FetchAssets (allPhotosOptions);
			PHFetchResult smartAlbums = PHAssetCollection.FetchAssetCollections (PHAssetCollectionType.SmartAlbum,
				PHAssetCollectionSubtype.AlbumRegular, null);

			PHFetchResult topLevelUserCollections = PHCollection.FetchTopLevelUserCollections (null);

			// Store the PHFetchResult objects and localized titles for each section.
			sectionFetchResults = new [] {
				allPhotos, smartAlbums, topLevelUserCollections
			};

			sectionLocalizedTitles = new [] {
				string.Empty, "Smart Albums", "Albums", string.Empty
			};

			PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver (this);
		}
Exemple #6
0
        void RetrieveLastAssetSaved()
        {
            var options = new PHFetchOptions();

            options.SortDescriptors = new NSSortDescriptor[] {
                new NSSortDescriptor("creationDate", false)
            };
            options.FetchLimit = 1;

            var result = PHAsset.FetchAssets(PHAssetMediaType.Video, options);

            if (result.firstObject != null)
            {
                var videoAsset = result.firstObject as PHAsset;
                if (videoAsset != null)
                {
                    PHImageManager.DefaultManager.RequestAvAsset(videoAsset, null, (asset, audioMix, info) =>
                    {
                        InvokeOnMainThread(() =>
                        {
                            FinalizeSave(((AVUrlAsset)asset).Url.AbsoluteString);
                        });
                    });
                }
                else
                {
                    Debug.WriteLine("FAIL");
                    //BTProgressHUD.Dismiss();
                }
            }
        }
Exemple #7
0
        private Task <OperationResult <LibraryMediaItem> > GetLastSavedMediaItem(MediaItemType itemType)
        {
            var tcs = new TaskCompletionSource <OperationResult <LibraryMediaItem> >();

            var fetchOptions = new PHFetchOptions();

            fetchOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) };
            var fetchResult = PHAsset.FetchAssets(itemType == MediaItemType.Video ? PHAssetMediaType.Video : PHAssetMediaType.Image, fetchOptions);
            var phAsset     = fetchResult?.firstObject as PHAsset;

            if (phAsset != null)
            {
                PHImageManager.DefaultManager.RequestAvAsset(phAsset, null, (asset, audioMix, info) =>
                {
                    var urlAsset = asset as AVUrlAsset;
                    tcs.SetResult(OperationResult <LibraryMediaItem> .AsSuccess(new LibraryMediaItem(phAsset.LocalIdentifier, urlAsset.Url.AbsoluteString)));
                });
            }
            else
            {
                tcs.SetResult(OperationResult <LibraryMediaItem> .AsFailure("Could not retrieve last asset"));
            }

            return(tcs.Task);
        }
Exemple #8
0
        private void FeetchAddPhotos()
        {
            PHPhotoLibrary.RequestAuthorization(status =>
            {
                if (status != PHAuthorizationStatus.Authorized)
                {
                    return;
                }

                var galleryTemp = new List <PHAssetCollection>();

                var allAlbums   = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, null).Cast <PHAssetCollection>();
                var smartAlbums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.SmartAlbumUserLibrary, null).Cast <PHAssetCollection>();

                galleryTemp.AddRange(allAlbums);
                galleryTemp.AddRange(smartAlbums);

                var gallerySort = galleryTemp.OrderBy(obj => obj.LocalizedTitle);

                NSOperationQueue.MainQueue.AddOperation(() =>
                {
                    foreach (var itemRaw in gallerySort)
                    {
                        var sortOptions             = new PHFetchOptions();
                        sortOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) };

                        var items = PHAsset.FetchAssets(itemRaw, sortOptions).Cast <PHAsset>().ToList();

                        if (items.Count > 0)
                        {
                            var colec = new GalleryNative()
                            {
                                Collection = itemRaw,
                            };
                            colec.Images.Add(new PhotoSetNative());

                            foreach (var item in items)
                            {
                                var newPhoto = new PhotoSetNative();
                                newPhoto.galleryImageXF.OriginalPath = item.LocalIdentifier;
                                newPhoto.Image = item;
                                colec.Images.Add(newPhoto);
                            }
                            galleryDirectories.Add(colec);
                        }
                    }

                    tableView.ReloadData();

                    if (galleryDirectories.Count > 0)
                    {
                        CurrentParent = 0;
                        IF_ItemSelectd(CurrentParent);
                    }
                });
            });
        }
Exemple #9
0
        private PHFetchResult PrepareResults()
        {
            var fetchOptions = new PHFetchOptions()
            {
                SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", true) }
            };

            return(PHAsset.FetchAssets(PHAssetMediaType.Image, fetchOptions));
        }
Exemple #10
0
        public PhotoCollectionViewSource()
        {
            PHFetchOptions options = new PHFetchOptions
            {
                SortDescriptors = new[] { new NSSortDescriptor("creationDate", false) },
            };

            _fetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, options);
            _m            = new PHImageManager();
        }
Exemple #11
0
        public static Task <PHAssetCollection> GetAlbum(string name)
        {
            var options = new PHFetchOptions();

            options.Predicate = NSPredicate.FromFormat("title = %@", NSObject.FromObject(name));
            var collection = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, options);

            return(collection.firstObject != null
                ? Task.FromResult((PHAssetCollection)collection.firstObject)
                : CreateAlbum(name));
        }
Exemple #12
0
        public async Task <GalleryImageXF> IF_SyncPhotoFromCloud(IGalleryPickerResultListener galleryPickerResultListener, GalleryImageXF imageSet, SyncPhotoOptions options)
        {
            try
            {
                bool FinishSync = false;

                Debug.WriteLine(imageSet.OriginalPath);

                var sortOptions = new PHFetchOptions();
                sortOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) };

                var FeechPhotoByIdentifiers = PHAsset.FetchAssetsUsingLocalIdentifiers(
                    new string[] { imageSet.OriginalPath },
                    sortOptions).Cast <PHAsset>().FirstOrDefault();

                if (FeechPhotoByIdentifiers != null)
                {
                    var requestOptions = new PHImageRequestOptions()
                    {
                        NetworkAccessAllowed = true,
                        DeliveryMode         = PHImageRequestOptionsDeliveryMode.HighQualityFormat,
                        ResizeMode           = PHImageRequestOptionsResizeMode.None,
                    };

                    var requestSize = new CoreGraphics.CGSize(options.Width, options.Height);
                    requestSize = PHImageManager.MaximumSize;

                    PHImageManager.DefaultManager.RequestImageForAsset(FeechPhotoByIdentifiers, requestSize, PHImageContentMode.AspectFit, requestOptions, (result, info) => {
                        if (result != null)
                        {
                            var newImage          = result.ResizeImage(options);
                            imageSet.ImageRawData = newImage.AsJPEG(options.Quality).ToArray();
                        }
                        FinishSync = true;
                    });

                    do
                    {
                        if (FinishSync)
                        {
                            return(imageSet);
                        }
                        await Task.Delay(1000);
                    } while (!FinishSync);
                }

                return(imageSet);
            }
            catch (Exception ex)
            {
                Debug.WriteLine(ex.StackTrace);
                return(imageSet);
            }
        }
        void GetPhotos()
        {
            if (PHPhotoLibrary.AuthorizationStatus == PHAuthorizationStatus.Authorized)
            {
                imageManager = PHImageManager.DefaultManager;

                PHFetchOptions options = new PHFetchOptions {
                    SortDescriptors = new [] { new NSSortDescriptor("creationDate", false) }
                };
                images = PHAsset.FetchAssets(PHAssetMediaType.Image, options);
                CollectionView.ReloadData();
            }
        }
Exemple #14
0
        public static PHFetchOptions FetchOptions(MediaType mediaType)
        {
            var options = new PHFetchOptions();

            switch (mediaType)
            {
            case MediaType.Photo:
                options.Predicate = NSPredicate.FromFormat(string.Format("mediaType == {0}", (int)PHAssetMediaType.Image));
                break;

            default:
                throw new NotSupportedException("not supported. Non photo types are not supported yet.");
            }

            return(options);
        }
        private void LoadAssetsFromLibrary()
        {
            var assetsOptions = new PHFetchOptions();

            // include all source types
            assetsOptions.IncludeAssetSourceTypes = PHAssetSourceType.CloudShared | PHAssetSourceType.UserLibrary | PHAssetSourceType.iTunesSynced;
            // show most recent first
            assetsOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("modificationDate", false) };

            // fecth videos
            this.assets = PHAsset.FetchAssets(PHAssetMediaType.Video, assetsOptions);

            // setup collection view
            this.RecalculateItemSize();
            this.CollectionView?.ReloadData();
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			ResetCachedAssets ();
			PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver (this);

			// If we get here without a segue, it's because we're visible at app launch,
			// so match the behavior of segue from the default "All Photos" view.
			if (FetchResult == null) {
				var allPhotosOptions = new PHFetchOptions {
					SortDescriptors = new NSSortDescriptor [] { new NSSortDescriptor ("creationDate", true) }
				};
				FetchResult = PHAsset.FetchAssets (allPhotosOptions);
			}
		}
Exemple #17
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            ResetCachedAssets();
            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);

            // If we get here without a segue, it's because we're visible at app launch,
            // so match the behavior of segue from the default "All Photos" view.
            if (FetchResult == null)
            {
                var allPhotosOptions = new PHFetchOptions {
                    SortDescriptors = new NSSortDescriptor [] { new NSSortDescriptor("creationDate", true) }
                };
                FetchResult = PHAsset.FetchAssets(allPhotosOptions);
            }
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			NavigationItem.RightBarButtonItem = new UIBarButtonItem (UIBarButtonSystemItem.Add, AddAlbum);

			// Create a PHFetchResult object for each section in the table view.
			var allPhotosOptions = new PHFetchOptions {
				SortDescriptors = new NSSortDescriptor [] { new NSSortDescriptor("creationDate", true) },
			};

			allPhotos = PHAsset.FetchAssets (allPhotosOptions);
			smartAlbums = PHAssetCollection.FetchAssetCollections (PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.AlbumRegular, null);
			userCollections = PHCollection.FetchTopLevelUserCollections (null);

			PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);
		}
Exemple #19
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            NavigationItem.RightBarButtonItem = new UIBarButtonItem(UIBarButtonSystemItem.Add, AddAlbum);

            // Create a PHFetchResult object for each section in the table view.
            var allPhotosOptions = new PHFetchOptions {
                SortDescriptors = new NSSortDescriptor [] { new NSSortDescriptor("creationDate", true) },
            };

            allPhotos       = PHAsset.FetchAssets(allPhotosOptions);
            smartAlbums     = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.AlbumRegular, null);
            userCollections = PHCollection.FetchTopLevelUserCollections(null);

            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);
        }
Exemple #20
0
        private static PHFetchResult FetchAssets()
        {
            const string sortType = "creationDate";

            var assetsOptions = new PHFetchOptions
            {
                SortDescriptors = new[]
                {
                    new NSSortDescriptor(sortType, false)
                },
                FetchLimit = FetchLimit
            };

            return(PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum,
                                                           PHAssetCollectionSubtype.SmartAlbumUserLibrary, null).firstObject is PHAssetCollection assetCollection
                ? PHAsset.FetchAssets(assetCollection, assetsOptions)
                : PHAsset.FetchAssets(assetsOptions));
        }
Exemple #21
0
        private async void SetGalleryButton()
        {
            var status = await PHPhotoLibrary.RequestAuthorizationAsync();

            if (status == PHAuthorizationStatus.Authorized)
            {
                var options = new PHFetchOptions
                {
                    SortDescriptors = new[] { new NSSortDescriptor("creationDate", false) },
                    FetchLimit      = 5,
                };

                var fetchedAssets    = PHAsset.FetchAssets(PHAssetMediaType.Image, options);
                var lastGalleryPhoto = fetchedAssets.FirstOrDefault() as PHAsset;
                if (lastGalleryPhoto != null)
                {
                    galleryButton.UserInteractionEnabled = true;
                    var PHImageManager = new PHImageManager();
                    PHImageManager.RequestImageForAsset(lastGalleryPhoto, new CGSize(300, 300),
                                                        PHImageContentMode.AspectFill, new PHImageRequestOptions()
                    {
                        DeliveryMode = PHImageRequestOptionsDeliveryMode.Opportunistic,
                        ResizeMode   = PHImageRequestOptionsResizeMode.Exact
                    }, (img, info) =>
                    {
                        galleryButton.Image = img;
                    });
                }
                else
                {
                    galleryButton.UserInteractionEnabled = false;
                }
            }
            else
            {
                galleryButton.UserInteractionEnabled = true;
            }
        }
Exemple #22
0
        public void BindDataToCell(GalleryNative galleryDirectory, Action action)
        {
            var count = galleryDirectory.Images.Count;

            txtTitle.Text       = galleryDirectory.Collection.LocalizedTitle;
            txtDescription.Text = "(" + count + ")";

            imageView.ClipsToBounds = true;
            imageView.ContentMode   = UIViewContentMode.ScaleAspectFill;

            try
            {
                var sortOptions = new PHFetchOptions();
                sortOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) };
                var items = PHAsset.FetchAssets(galleryDirectory.Collection, sortOptions).Cast <PHAsset>().ToList();

                var options = new PHImageRequestOptions
                {
                    Synchronous = true
                };
                PHImageManager.DefaultManager.RequestImageForAsset(items[0], imageView.Bounds.Size, PHImageContentMode.AspectFit, options, (requestedImage, _) => {
                    imageView.Image = requestedImage;
                });
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.StackTrace);
            }

            if (ActionClick == null)
            {
                ActionClick             = action;
                bttClick.TouchUpInside += (sender, e) =>
                {
                    ActionClick();
                };
            }
        }
Exemple #23
0
        private void OnAuthorized()
        {
            DispatchQueue.MainQueue.DispatchAsync(() =>
            {
                _imageManager = new PHCachingImageManager();

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

                var assets = new List <PHAsset>();

                if (_mediaTypes.HasFlag(MediaType.Image))
                {
                    _images = PHAsset.FetchAssets(PHAssetMediaType.Image, options);
                    assets.AddRange(_images.OfType <PHAsset>());
                }

                if (_mediaTypes.HasFlag(MediaType.Video))
                {
                    _videos = PHAsset.FetchAssets(PHAssetMediaType.Video, options);
                    assets.AddRange(_videos.OfType <PHAsset>());
                }

                foreach (var asset in assets.OrderByDescending(a => a.CreationDate.SecondsSinceReferenceDate))
                {
                    AllAssets.Add(asset);
                }

                ShowFirstImage();

                AllAssets.CollectionChanged += AssetsCollectionChanged;
                PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);
            });
        }
			private async void PerformLoadAssets ()
			{
				var options = new PHFetchOptions ();
				options.SortDescriptors = new [] { new NSSortDescriptor ("creationDate", false) };
				assets = await Task.Run (() => PHAsset.FetchAssets (options).Cast<PHAsset> ().ToList ());
				if (assets.Count > 0) {
					tableView.ReloadData ();
				}
			}
Exemple #25
0
 public static PHFetchResult FetchMoments(PHFetchOptions options)
 {
     return(null);
 }
Exemple #26
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);
        }
Exemple #27
0
 public static PHFetchResult FetchMoments(PHCollectionList momentList, PHFetchOptions options)
 {
     return(null);
 }
Exemple #28
0
        private void UpdateFetchResults()
        {
            //What I do here is fetch both the albums list and the assets of each album.
            //This way I have acces to the number of items in each album, I can load the 3
            //thumbnails directly and I can pass the fetched result to the gridViewController.
            _collectionsFetchResultsAssets = null;
            _collectionsFetchResultsTitles = null;

            //Fetch PHAssetCollections:
            var topLevelUserCollections = _collectionsFetchResults[0];
            var smartAlbums             = _collectionsFetchResults[1];

            // All album: Sorted by descending creation date.
            var allFetchResults      = new List <PHFetchResult>();
            var allFetchResultLabels = new List <string> ();

            var options = new PHFetchOptions {
                Predicate       = NSPredicate.FromFormat("mediaType in %@", ToNSArray(_picker.MediaTypes)),
                SortDescriptors = new [] { new NSSortDescriptor("creationDate", _picker.GridSortOrder == SortOrder.Ascending) },
            };
            var assetsFetchResult = PHAsset.FetchAssets(options);

            allFetchResults.Add(assetsFetchResult);
            allFetchResultLabels.Add("picker.table.all-photos-label".Translate(defaultValue: "All photos"));

            //User albums:
            var userFetchResults      = new List <PHFetchResult>();
            var userFetchResultLabels = new List <string> ();

            foreach (var assetCollection in topLevelUserCollections.OfType <PHAssetCollection>())
            {
                var collectionOptions = new PHFetchOptions {
                    Predicate       = NSPredicate.FromFormat("mediaType in %@", ToNSArray(_picker.MediaTypes)),
                    SortDescriptors = new[] { new NSSortDescriptor("creationDate", _picker.GridSortOrder == SortOrder.Ascending) },
                };

                //Albums collections are always PHAssetCollectionType=1 & PHAssetCollectionSubtype=2
                var collectionAssetsFetchResult = PHAsset.FetchAssets(assetCollection, collectionOptions);
                userFetchResults.Add(collectionAssetsFetchResult);
                userFetchResultLabels.Add(assetCollection.LocalizedTitle);
            }

            //Smart albums: Sorted by descending creation date.
            var smartFetchResults      = new List <PHFetchResult>();
            var smartFetchResultLabels = new List <string> ();

            foreach (var assetCollection in smartAlbums.OfType <PHAssetCollection>())
            {
                //Smart collections are PHAssetCollectionType=2;
                if (_picker.CustomSmartCollections != null && _picker.CustomSmartCollections.Contains(assetCollection.AssetCollectionSubtype))
                {
                    var smartFetchOptions = new PHFetchOptions {
                        Predicate       = NSPredicate.FromFormat("mediaType in %@", ToNSArray(_picker.MediaTypes)),
                        SortDescriptors = new [] { new NSSortDescriptor("creationDate", _picker.GridSortOrder == SortOrder.Ascending) },
                    };

                    var smartAssetsFetchResult = PHAsset.FetchAssets(assetCollection, smartFetchOptions);
                    if (smartAssetsFetchResult.Any())
                    {
                        smartFetchResults.Add(smartAssetsFetchResult);
                        smartFetchResultLabels.Add(assetCollection.LocalizedTitle);
                    }
                }
            }


            _collectionsFetchResultsAssets = new PHFetchResult[][] {
                allFetchResults.ToArray(),
                    userFetchResults.ToArray(),
                    smartFetchResults.ToArray()
            };
            _collectionsFetchResultsTitles = new string[][] {
                allFetchResultLabels.ToArray(),
                    userFetchResultLabels.ToArray(),
                    smartFetchResultLabels.ToArray()
            };
        }
Exemple #29
0
 public static PHFetchResult FetchMomentLists(PHCollectionListSubtype subType, PHAssetCollection moment, PHFetchOptions options)
 {
     return(null);
 }
        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);
        }
        public Task <SupportImageXF> IF_SyncPhotoFromCloud(SupportImageXF imageSet, SyncPhotoOptions options)
        {
            ManualResetEvent manualResetEvent = new ManualResetEvent(false);

            return(Task.Factory.StartNew(() => {
                try
                {
                    manualResetEvent.Reset();

                    var sortOptions = new PHFetchOptions();
                    sortOptions.SortDescriptors = new NSSortDescriptor[] { new NSSortDescriptor("creationDate", false) };

                    var FeechPhotoByIdentifiers = PHAsset.FetchAssetsUsingLocalIdentifiers(
                        new string[] { imageSet.OriginalPath },
                        sortOptions).Cast <PHAsset>().FirstOrDefault();

                    Console.WriteLine(imageSet.OriginalPath + "  ==> Run at step 1");

                    if (FeechPhotoByIdentifiers != null)
                    {
                        var requestOptions = new PHImageRequestOptions()
                        {
                            NetworkAccessAllowed = true,
                            DeliveryMode = PHImageRequestOptionsDeliveryMode.HighQualityFormat,
                            ResizeMode = PHImageRequestOptionsResizeMode.None,
                        };

                        var requestSize = PHImageManager.MaximumSize;

                        Console.WriteLine(imageSet.OriginalPath + "  ==> Run at step 2");

                        PHImageManager.DefaultManager.RequestImageForAsset(FeechPhotoByIdentifiers, requestSize, PHImageContentMode.AspectFit, requestOptions, (image, info) => {
                            Console.WriteLine(imageSet.OriginalPath + "  ==> Run at step 3");
                            if (image != null)
                            {
                                //var newImage = result.ResizeImage(options);
                                //imageSet.ImageRawData = newImage.AsJPEG(options.Quality).ToArray();
                                try
                                {
                                    var url = info.ObjectForKey(new NSString("PHImageFileURLKey")) as NSUrl;
                                    if (url == null)
                                    {
                                        // Get image and save to file
                                        var filePath = Path.Combine(Path.GetTempPath(), $"Photo_{Path.GetTempFileName()}");
                                        image.AsJPEG().Save(filePath, false, out _);
                                        url = new NSUrl(filePath);
                                    }

                                    var fileName = url.Path;
                                    var newWidth = image.Size.Width;
                                    var newHeight = image.Size.Height;

                                    // Create temp file path
                                    var fileNameOnly = Path.GetFileNameWithoutExtension(fileName);
                                    var fileExtension = Path.GetExtension(fileName);
                                    var newFileName = fileNameOnly + "_" + DateTime.Now.ToFormatString("yyyyMMddHHmmss") + "_" + newWidth + "x" + newHeight + fileExtension;
                                    var tempPath = Path.Combine(Path.GetTempPath(), newFileName);
                                    FileHelper.CreateFile(tempPath);

                                    // Write data to temp file
                                    using (var newStream = FileHelper.GetWriteFileStream(tempPath))
                                    {
                                        using (var imageData = image.AsJPEG())
                                        {
                                            var buffer = new byte[imageData.Length];
                                            System.Runtime.InteropServices.Marshal.Copy(imageData.Bytes, buffer, 0, Convert.ToInt32(imageData.Length));
                                            newStream.Write(buffer, 0, buffer.Length);

                                            imageSet.ProcessFilePath = tempPath;
                                            //Console.WriteLine("Finish item at ==> " + tempPath);
                                        }
                                    }
                                    Console.WriteLine(imageSet.OriginalPath + "  ==> Run at step 4");
                                    manualResetEvent.Set();
                                }
                                catch (Exception ex)
                                {
                                    // Ignore
                                    Console.WriteLine("Error for " + imageSet.OriginalPath);
                                    Console.WriteLine(ex.StackTrace);
                                    manualResetEvent.Set();
                                }
                            }
                            else
                            {
                                Console.WriteLine("Can not sync image");
                                manualResetEvent.Set();
                            }
                        });
                    }
                    else
                    {
                        Console.WriteLine(imageSet.OriginalPath + "  ==> Run at step 5");
                        manualResetEvent.Set();
                    }

                    manualResetEvent.WaitOne();

                    return imageSet;
                }
                catch (Exception ex)
                {
                    Console.WriteLine(ex);
                    return imageSet;
                }
            }));
        }
		private void UpdateFetchResults()
		{
			//What I do here is fetch both the albums list and the assets of each album.
			//This way I have acces to the number of items in each album, I can load the 3
			//thumbnails directly and I can pass the fetched result to the gridViewController.
			_collectionsFetchResultsAssets = null;
			_collectionsFetchResultsTitles = null;

			//Fetch PHAssetCollections:
			var topLevelUserCollections = _collectionsFetchResults[0];
			var smartAlbums = _collectionsFetchResults[1];

			// All album: Sorted by descending creation date.
			var allFetchResults = new List<PHFetchResult>();
			var allFetchResultLabels = new List<string> ();

			var options = new PHFetchOptions {
				Predicate = NSPredicate.FromFormat("mediaType in %@", ToNSArray(_picker.MediaTypes)),
				SortDescriptors = new [] { new NSSortDescriptor("creationDate", _picker.GridSortOrder == SortOrder.Ascending) },
			};
			var assetsFetchResult = PHAsset.FetchAssets (options);
			allFetchResults.Add (assetsFetchResult);
			allFetchResultLabels.Add ("picker.table.all-photos-label".Translate (defaultValue: "All photos"));

			//User albums:
			var userFetchResults = new List<PHFetchResult>();
			var userFetchResultLabels = new List<string> ();

			foreach (PHCollection collection in topLevelUserCollections) {
				if (collection is PHAssetCollection) {
					var collectionOptions = new PHFetchOptions {
						Predicate = NSPredicate.FromFormat("mediaType in %@", ToNSArray(_picker.MediaTypes)),
                        SortDescriptors = new[] { new NSSortDescriptor("creationDate", _picker.GridSortOrder == SortOrder.Ascending) },
                    };
					var assetCollection = (PHAssetCollection)collection;

					//Albums collections are always PHAssetCollectionType=1 & PHAssetCollectionSubtype=2
					var collectionAssetsFetchResult = PHAsset.FetchKeyAssets(assetCollection, collectionOptions);
					userFetchResults.Add (collectionAssetsFetchResult);
					userFetchResultLabels.Add (collection.LocalizedTitle);
				}
			}

			//Smart albums: Sorted by descending creation date.
			var smartFetchResults = new List<PHFetchResult>();
			var smartFetchResultLabels = new List<string> ();

			foreach (PHCollection collection in smartAlbums) {
				if (collection is PHAssetCollection) {
					var assetCollection = (PHAssetCollection)collection;

					//Smart collections are PHAssetCollectionType=2;
					if (_picker.CustomSmartCollections != null && _picker.CustomSmartCollections.Contains (assetCollection.AssetCollectionSubtype)) {
						var smartFetchOptions = new PHFetchOptions {
							Predicate = NSPredicate.FromFormat("mediaType in %@", ToNSArray(_picker.MediaTypes)),
							SortDescriptors = new [] { new NSSortDescriptor ("creationDate", _picker.GridSortOrder == SortOrder.Ascending) },
						};

						var smartAssetsFetchResult = PHAsset.FetchKeyAssets (assetCollection, smartFetchOptions);
						if (smartAssetsFetchResult.Any ()) {
							smartFetchResults.Add (smartAssetsFetchResult);
							smartFetchResultLabels.Add (collection.LocalizedTitle);
						}
					}
				}
			}

			_collectionsFetchResultsAssets = new PHFetchResult[][] {
				allFetchResults.ToArray (),
				userFetchResults.ToArray (),
				smartFetchResults.ToArray ()
			};
			_collectionsFetchResultsTitles = new string[][] { 
				allFetchResultLabels.ToArray (),
				userFetchResultLabels.ToArray (),
				smartFetchResultLabels.ToArray ()
			};
		}
Exemple #33
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            var rotateTap = new UITapGestureRecognizer(RotateTap);

            rotate.AddGestureRecognizer(rotateTap);

            var zoomTap = new UITapGestureRecognizer(ZoomTap);

            resize.AddGestureRecognizer(zoomTap);

            var multiselectTap = new UITapGestureRecognizer(MultiSelectTap);

            multiSelect.AddGestureRecognizer(multiselectTap);

            bottomArrow.Transform = CGAffineTransform.MakeRotation((float)(Math.PI));

            source = new PhotoCollectionViewSource(_m);
            photoCollection.Source = source;
            photoCollection.RegisterClassForCell(typeof(PhotoCollectionViewCell), nameof(PhotoCollectionViewCell));

            photoCollection.SetCollectionViewLayout(new UICollectionViewFlowLayout()
            {
                ItemSize                = Constants.CellSize,
                MinimumLineSpacing      = 1,
                MinimumInteritemSpacing = 1,
            }, false);

            delegateP = new PhotoCollectionViewFlowDelegate(source);
            photoCollection.Delegate = delegateP;

            delegateP.CellClicked += CellAction;

            _cropView = new CropView(new CGRect(0, 0, UIScreen.MainScreen.Bounds.Width, UIScreen.MainScreen.Bounds.Width));

            _cropView.ZoomingStarted += (object sender, UIScrollViewZoomingEventArgs e) =>
            {
                NavigationItem.RightBarButtonItem.Enabled = false;
            };

            _cropView.ZoomingEnded += (object sender, ZoomingEndedEventArgs e) =>
            {
                NavigationItem.RightBarButtonItem.Enabled = true;
            };

            var albums       = new List <PHAssetCollection>();
            var sortedAlbums = new List <Tuple <string, PHFetchResult> >();
            var fetchOptions = new PHFetchOptions();

            var allAlbums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.AlbumRegular, null)
                            .Cast <PHAssetCollection>();

            albums.AddRange(allAlbums);
            var smartAlbums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.AlbumRegular, null)
                              .Cast <PHAssetCollection>();

            albums.AddRange(smartAlbums);
            fetchOptions.Predicate = NSPredicate.FromFormat("mediaType == %d", FromObject(PHAssetMediaType.Image));

            foreach (var item in albums)
            {
                var firstAsset = PHAsset.FetchAssets(item, fetchOptions);
                if (firstAsset.Count > 0)
                {
                    sortedAlbums.Add(new Tuple <string, PHFetchResult>(item.LocalizedTitle, firstAsset));
                }
            }

            sortedAlbums = sortedAlbums.OrderByDescending(a => a.Item2.Count).ToList();

            _modalFolderView.BackgroundColor = UIColor.White;

            var folderTable = new UITableView();

            folderTable.Bounces         = false;
            folderTable.AllowsSelection = false;
            folderTable.RowHeight       = 90;
            folderTable.SeparatorStyle  = UITableViewCellSeparatorStyle.None;
            var folderSource = new FolderTableViewSource(sortedAlbums);

            folderSource.CellAction += (ActionType arg1, Tuple <string, PHFetchResult> arg2) =>
            {
                TitleTapped();
                _titleLabel.Text = arg2.Item1;
                source.UpdateFetchResult(arg2.Item2);
                photoCollection.SetContentOffset(new CGPoint(0, 0), false);
                photoCollection.ReloadData();
                if (!source.MultiPickMode)
                {
                    delegateP.ItemSelected(photoCollection, NSIndexPath.FromItemSection(0, 0));
                }
            };
            folderTable.Source = folderSource;
            _modalFolderView.AddSubview(folderTable);
            folderTable.RegisterClassForCellReuse(typeof(AlbumTableViewCell), nameof(AlbumTableViewCell));
            folderTable.AutoPinEdgesToSuperviewEdges();
            folderTable.ReloadData();

            cropBackgroundView.BackgroundColor = Constants.R245G245B245;
            cropBackgroundView.AddSubview(_cropView);
            NavigationController.NavigationBar.Translucent = false;
            SetBackButton();

            _titleLabel.Text = sortedAlbums.FirstOrDefault()?.Item1;
            source.UpdateFetchResult(sortedAlbums.FirstOrDefault()?.Item2);
        }