Esempio n. 1
0
        public override void PrepareForSegue(UIStoryboardSegue segue, NSObject sender)
        {
            if (!(segue.DestinationViewController is AssetGridViewController) || !(sender is UITableViewCell))
            {
                return;
            }

            var assetGridViewController = (AssetGridViewController)segue.DestinationViewController;
            var cell = (UITableViewCell)sender;

            // Set the title of the AssetGridViewController.
            assetGridViewController.Title = cell.TextLabel.Text;

            // Get the PHFetchResult for the selected section.
            NSIndexPath   indexPath   = TableView.IndexPathForCell(cell);
            PHFetchResult fetchResult = sectionFetchResults [indexPath.Section];

            if (segue.Identifier == allPhotosSegue)
            {
                assetGridViewController.AssetsFetchResults = fetchResult;
            }
            else if (segue.Identifier == collectionSegue)
            {
                // Get the PHAssetCollection for the selected row.
                var collection = fetchResult [indexPath.Row] as PHAssetCollection;
                if (collection == null)
                {
                    return;
                }
                var assetsFetchResult = PHAsset.FetchAssets(collection, null);

                assetGridViewController.AssetsFetchResults = assetsFetchResult;
                assetGridViewController.AssetCollection    = collection;
            }
        }
Esempio n. 2
0
        private PHFetchResult AdjustAssets(PHFetchResult assets, PHFetchResultChangeDetails changes)
        {
            if (assets == null)
            {
                return(null);
            }

            var before = assets;

            assets = changes.FetchResultAfterChanges;

            foreach (var asset in before.OfType <PHAsset>())
            {
                if (!assets.Contains(asset))
                {
                    AllAssets.Remove(asset);
                }
            }

            foreach (var asset in assets.OfType <PHAsset>().OrderBy(a => a.CreationDate.SecondsSinceReferenceDate))
            {
                if (!AllAssets.Contains(asset))
                {
                    AllAssets.Insert(0, asset);
                }
            }

            return(assets);
        }
Esempio n. 3
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);
        }
Esempio n. 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();
        }
Esempio n. 5
0
        public void PhotoLibraryDidChange(PHChange changeInstance)
        {
            // Change notifications may be made on a background queue. Re-dispatch to the
            // main queue before acting on the change as we'll be updating the UI.
            DispatchQueue.MainQueue.DispatchSync(() =>
            {
                // Check each of the three top-level fetches for changes.

                // Update the cached fetch result.
                var changeDetails = changeInstance.GetFetchResultChangeDetails(allPhotos);
                if (changeDetails != null)
                {
                    // Update the cached fetch result.
                    allPhotos = changeDetails.FetchResultAfterChanges;
                    // (The table row for this one doesn't need updating, it always says "All Photos".)
                }

                // Update the cached fetch results, and reload the table sections to match.
                changeDetails = changeInstance.GetFetchResultChangeDetails(smartAlbums);
                if (changeDetails != null)
                {
                    smartAlbums = changeDetails.FetchResultAfterChanges;
                    TableView.ReloadSections(NSIndexSet.FromIndex((int)Section.SmartAlbums), UITableViewRowAnimation.Automatic);
                }

                changeDetails = changeInstance.GetFetchResultChangeDetails(userCollections);
                if (changeDetails != null)
                {
                    userCollections = changeDetails.FetchResultAfterChanges;
                    TableView.ReloadSections(NSIndexSet.FromIndex((int)Section.UserCollections), UITableViewRowAnimation.Automatic);
                }
            });
        }
        // TODO MAKE ASYNC
        public List <ImageMediaContent> loadImages()
        {
            List <ImageMediaContent> imageMedia = new List <ImageMediaContent>();

            PHFetchResult fetchResult = PHAsset.FetchAssets(PHAssetMediaType.Image, null);

            nint index = 0;

            foreach (PHAsset phAsset in fetchResult)
            {
                String filePath = "";

                UIImage image;

                imageManager.RequestImageForAsset((PHAsset)imageFetchResults[index], new SizeF(160, 160),
                                                  PHImageContentMode.AspectFill, new PHImageRequestOptions(), (img, info) =>
                {
                    image = img;
                });

                index++;

                phAsset.RequestContentEditingInput(new PHContentEditingInputRequestOptions(), (input, v) =>
                {
                    filePath = input.FullSizeImageUrl.Path;
                });

                imageMedia.Add(new ImageMediaContent(filePath));
            }

            return(imageMedia);
        }
Esempio n. 7
0
        void ImageEditor_ImageSaved(object sender, ImageSavedEventArgs e)
        {
            string[]      str         = e.Location.Split('/');
            PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null);
            PHAsset       asset       = assetResult.firstObject as PHAsset;
            Stream        stream      = null;

            PHImageManager.DefaultManager.RequestImageData(asset, null, async(data, dataUti, orientation, info) =>
            {
                UIImage newImage       = new UIImage(data);
                var items              = new NSObject[] { newImage };
                var activityController = new UIActivityViewController(items, null);


                NSString[] excludedActivityTypes = null;

                if (excludedActivityTypes != null && excludedActivityTypes.Length > 0)
                {
                    activityController.ExcludedActivityTypes = excludedActivityTypes;
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    if (activityController.PopoverPresentationController != null)
                    {
                        activityController.PopoverPresentationController.SourceView = presentController.View;
                    }
                }

                await presentController.PresentViewControllerAsync(activityController, true);
            });
        }
Esempio n. 8
0
        /// <summary>
        /// MUST BE CALLED FROM THE UI THREAD
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="title"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public async Task Show(string title, string message, string filePath)
        {
            string[]      str         = filePath.Split('/');
            PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null);
            PHAsset       asset       = assetResult.firstObject as PHAsset;
            Stream        stream      = null;

            PHImageManager.DefaultManager.RequestImageData(asset, null, async(data, dataUti, orientation, info) =>
            {
                UIImage newImage       = new UIImage(data);
                var items              = new NSObject[] { newImage };
                var activityController = new UIActivityViewController(items, null);
                var vc = GetVisibleViewController();

                NSString[] excludedActivityTypes = null;

                if (excludedActivityTypes != null && excludedActivityTypes.Length > 0)
                {
                    activityController.ExcludedActivityTypes = excludedActivityTypes;
                }

                if (UIDevice.CurrentDevice.CheckSystemVersion(8, 0))
                {
                    if (activityController.PopoverPresentationController != null)
                    {
                        activityController.PopoverPresentationController.SourceView = vc.View;
                    }
                }

                await vc.PresentViewControllerAsync(activityController, true);
            });
        }
Esempio n. 9
0
        /// <summary>
        /// MUST BE CALLED FROM THE UI THREAD
        /// </summary>
        /// <param name="filePath"></param>
        /// <param name="title"></param>
        /// <param name="message"></param>
        /// <returns></returns>
        public void Show(string title, string message, string filePath)
        {
            string[]      str         = filePath.Split('/');
            PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null);
            PHAsset       asset       = assetResult.firstObject as PHAsset;

            PHImageManager.DefaultManager.RequestImageData(asset, null, HandlePHImageDataHandler);
        }
Esempio n. 10
0
        public iOSPhotoLibraryChangeObserver(iOSImageMetadataProbe probe, DispatchQueue dispatchQueue)
        {
            _probe         = probe;
            _dispatchQueue = dispatchQueue;

            _imageFetchResult = PHAsset.FetchAssets(PHAssetMediaType.Image, new PHFetchOptions());
            _videoFetchResult = PHAsset.FetchAssets(PHAssetMediaType.Video, new PHFetchOptions());
        }
Esempio n. 11
0
 /// <summary>
 /// Photo Library change observer. Triggers when changes are made to the photo library such as
 /// new pictures were added or pictures were removed
 /// </summary>
 /// <param name="changeInstance"><see cref="PHChange"/> with changes</param>
 public void PhotoLibraryDidChange(PHChange changeInstance)
 {
     DispatchQueue.MainQueue.DispatchAsync(() =>
     {
         _images = TryAdjustAssets(_images, changeInstance);
         _videos = TryAdjustAssets(_videos, changeInstance);
     });
 }
Esempio n. 12
0
        public PhotoCollectionViewSource()
        {
            PHFetchOptions options = new PHFetchOptions
            {
                SortDescriptors = new[] { new NSSortDescriptor("creationDate", false) },
            };

            _fetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, options);
            _m            = new PHImageManager();
        }
        public PhotosViewController(UICollectionViewLayout layout) : base(layout)
        {
            Title = "All Photos";

            imageMgr     = new PHImageManager();
            fetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, null);

            observer = new PhotoLibraryObserver(this);

            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(observer);
        }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad();

			ScreenName = $"{GAIKeys.ScreenNames.BugDetails} ({TrackerService.Shared.CurrentTracker})";

			thumbSize = new CGSize (125.0 * UIScreen.MainScreen.Scale, 125.0 * UIScreen.MainScreen.Scale);

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

			assetsFetchResult = PHAsset.FetchAssetsUsingLocalIdentifiers(TrapState.Shared.LocalIdentifiersForActiveSnapshots, options);
		}
        public PhotosViewController(UICollectionViewLayout layout)
            : base(layout)
        {
            Title = "All Photos";

            imageMgr = new PHImageManager ();
            fetchResults = PHAsset.FetchAssets (PHAssetMediaType.Image, null);

            observer = new PhotoLibraryObserver (this);

            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver (observer);
        }
        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();
            }
        }
        public UILatestPhotosOverlayView(CGRect frame) : base(frame, new UIHorizontalScrollLayout())
        {
            DataSource = this;
            RegisterClassForCell(typeof(UIImageViewCell), imageViewCellId);
            fetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, null);
            manager      = new PHImageManager();

            var tapRecognizer = new UITapGestureRecognizer(() => Console.Write("test"));

            AddGestureRecognizer(tapRecognizer);
            TranslatesAutoresizingMaskIntoConstraints = false;
            BackgroundColor = UIColor.Clear;
        }
		public BtImageCollectionViewController (IntPtr handle) : base(handle)
		{
			fetchOptions.SortDescriptors = new [] { new NSSortDescriptor ("modificationDate", false) };

			// delay requesting permission for Test Cloud runs so it doesn't crash
			Task.Run(async() => {
				#if UITEST
				await Task.Delay(3000);
				#endif
				await TrapState.Shared.GetAlbumLocalIdentifier();
				assetsFetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, fetchOptions);
			});
		}
Esempio n. 19
0
        public async Task GetAllThumbnails(List <ItemModel> items)
        {
            await Task.Run(() =>
            {
                PHFetchResult fetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, null);

                foreach (PHAsset asset in fetchResults)
                {
                    items.Add(new ItemModel {
                        ThumbLoader = new ThumbLoader_iOS(asset), ModificationDate = asset.ModificationDate.ToDateTime()
                    });
                }
            });
        }
		public override void ViewWillAppear (bool animated)
		{
			base.ViewWillAppear(animated);

			NavigationController.HidesBarsOnTap = false;

			if (!IsMovingToParentViewController) {
				var state = TrackerService.Shared.CurrentTracker.TrackerState;
				TableView.ReloadSections(NSIndexSet.FromIndex(state.ActiveBugDetail), UITableViewRowAnimation.Automatic);
			}

			assetsFetchResult = PHAsset.FetchAssetsUsingLocalIdentifiers(TrapState.Shared.LocalIdentifiersForActiveSnapshots, options);
			reloadEmbeddedImageCollectinView();
		}
        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 ();

			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);
		}
Esempio n. 23
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);
        }
Esempio n. 24
0
        public override nint RowsInSection(UITableView tableView, nint section)
        {
            nint numberOfRows;

            if (section == 0)
            {
                // The "All Photos" section only ever has a single row.
                numberOfRows = 1;
            }
            else
            {
                PHFetchResult fetchResult = sectionFetchResults[section];
                numberOfRows = fetchResult.Count;
            }

            return(numberOfRows);
        }
Esempio n. 25
0
        partial void BtnClick(UIKit.UIButton sender)
        {
            PHFetchResult fetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, null);

            for (int i = 0; i < fetchResults.Count; i++)
            {
                //fetching Result
                PHAsset phAsset  = (PHAsset)fetchResults[i];
                String  fileName = (NSString)phAsset.ValueForKey((NSString)"filename");
                PHImageManager.DefaultManager.RequestImageData(phAsset, null, (data, dataUti, orientation, info) =>
                {
                    var path = (info?[(NSString)@"PHImageFileURLKey"] as NSUrl).FilePathUrl.Path;
                    //Stream stream = System.IO.OpenRead((String)path);

                    Stream stream = new FileStream(path, FileMode.Open, FileAccess.Read);
                });
            }
        }
Esempio n. 26
0
        private PHFetchResult TryAdjustAssets(PHFetchResult assets, PHChange changeInstance)
        {
            if (assets == null)
            {
                return(null);
            }

            if (changeInstance == null)
            {
                return(assets);
            }

            var collectionChanges = changeInstance.GetFetchResultChangeDetails(assets);

            if (collectionChanges == null)
            {
                return(assets);
            }

            return(AdjustAssets(assets, collectionChanges));
        }
Esempio n. 27
0
        public override UITableViewCell GetCell(UITableView tableView, NSIndexPath indexPath)
        {
            UITableViewCell cell;

            if (indexPath.Section == 0)
            {
                cell = TableView.DequeueReusableCell(allPhotosReuseIdentifier, indexPath);
                cell.TextLabel.Text = "All Photos";
            }
            else
            {
                PHFetchResult fetchResult = sectionFetchResults [indexPath.Section];
                var           collections = fetchResult.Cast <PHCollection> ().ToArray();
                var           collection  = collections [indexPath.Row];

                cell = TableView.DequeueReusableCell(collectionCellReuseIdentifier, indexPath);
                cell.TextLabel.Text = collection.LocalizedTitle;
            }

            return(cell);
        }
Esempio n. 28
0
        public void LoadSampleStream(string filename, SerializationModel model)
        {
            try
            {
                string[] str = filename.Split('/');

                PHFetchResult assetResult = PHAsset.FetchAssetsUsingLocalIdentifiers(str, null);
                PHAsset       asset       = assetResult.firstObject as PHAsset;
                Stream        stream      = new MemoryStream();
                PHImageManager.DefaultManager.RequestImageData(asset, null, (data, dataUti,
                                                                             orientation, info) =>
                {
                    byte[] byteArray = data.ToArray();
                    Stream streamm   = new MemoryStream(byteArray);
                    dictionary.Add(filename, streamm);
                    model.Location = filename;
                });
            }
            catch (Exception)
            {
            }
        }
Esempio n. 29
0
        public override void PhotoLibraryDidChange(PHChange changeInstance)
        {
            PHFetchResultChangeDetails imageDetails    = changeInstance.GetFetchResultChangeDetails(_imageFetchResult);
            PHFetchResultChangeDetails videoDetails    = changeInstance.GetFetchResultChangeDetails(_videoFetchResult);
            List <PHObject>            insertedObjects = new List <PHObject>();

            if (imageDetails != null && imageDetails.InsertedObjects.Any())
            {
                insertedObjects.AddRange(imageDetails.InsertedObjects);

                _imageFetchResult = imageDetails.FetchResultAfterChanges;
            }

            if (videoDetails != null && videoDetails.InsertedObjects.Any())
            {
                insertedObjects.AddRange(videoDetails.InsertedObjects);

                _videoFetchResult = videoDetails.FetchResultAfterChanges;
            }

            HandleImage(insertedObjects);
        }
Esempio n. 30
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);
            });
        }
Esempio n. 31
0
        public void PhotoLibraryDidChange(PHChange changeInstance)
        {
            Debug.WriteLine($"{this.GetType().Name}: PhotoLibraryDidChange");

            // Call might come on any background queue. Re-dispatch to the main queue to handle it.
            DispatchQueue.MainQueue.DispatchAsync(() => {
                // check if there are changes to the assets (insertions, deletions, updates)
                var collectionChanges = changeInstance.GetFetchResultChangeDetails(AssetsFetchResults);
                if (collectionChanges != null)
                {
                    var collectionView = CollectionView;
                    if (CollectionView == null)
                    {
                        return;
                    }

                    // get the new fetch result
                    AssetsFetchResults = collectionChanges.FetchResultAfterChanges;

                    if (!collectionChanges.HasIncrementalChanges || collectionChanges.HasMoves)
                    {
                        // we need to reload all if the incremental diffs are not available
                        collectionView.ReloadData();
                    }
                    else
                    {
                        // if we have incremental diffs, tell the collection view to animate insertions and deletions
                        collectionView.PerformBatchUpdates(() =>
                        {
                            var removedIndexes = collectionChanges.RemovedIndexes;
                            if (removedIndexes != null && removedIndexes.Count > 0)
                            {
                                collectionView.DeleteItems(GetIndexesWithSection(removedIndexes, 0));
                            }

                            if (collectionChanges.InsertedIndexes != null && collectionChanges.InsertedIndexes.Count > 0)
                            {
                                collectionView.InsertItems(GetIndexesWithSection(collectionChanges.InsertedIndexes, 0));

                                var changedIndexes = collectionChanges.ChangedIndexes;
                                if (changedIndexes != null && changedIndexes.Count > 0)
                                {
                                    collectionView.ReloadItems(GetIndexesWithSection(changedIndexes, 0));
                                }
                            }
                        }, (x) => {
                            if (_picker.GridSortOrder == SortOrder.Ascending)
                            {
                                var item = collectionView.NumberOfItemsInSection(0) - 1;
                                if (item >= 0)
                                {
                                    var path = NSIndexPath.FromItemSection(item, 0);
                                    collectionView.ScrollToItem(path, UICollectionViewScrollPosition.Bottom, true);
                                }
                            }
                            else
                            {
                                var path = NSIndexPath.FromItemSection(0, 0);
                                collectionView.ScrollToItem(path, UICollectionViewScrollPosition.Top, true);
                            }
                        });

                        if (collectionChanges.InsertedIndexes != null && collectionChanges.InsertedIndexes.Count > 0)
                        {
                            if (_picker.ShowCameraButton && _picker.AutoSelectCameraImages)
                            {
                                foreach (var path in GetIndexesWithSection(collectionChanges.InsertedIndexes, 0))
                                {
                                    ItemSelected(collectionView, path);
                                }
                            }
                        }
                    }
                    ResetCachedAssets();
                }
            });
        }
Esempio n. 32
0
 public void Update(Action handler = null)
 {
     _fetchResult = PHAsset.FetchAssets(_assetList, FetchOptions(_mediaType));
     handler?.Invoke();
 }
		void updateViewConfiguration (bool animate = true, bool reloadData = false, bool updateScreenName = true, bool showActivity = false)
		{
			if (GetItemsCount(CollectionView, 0) == 0 && !noImageView.IsDescendantOfView(View)) {
				View.AddSubview(noImageView);
			} else if (noImageView.IsDescendantOfView(View)) {
				noImageView.RemoveFromSuperview();
			}

			if (updateScreenName) UpdateScreenName(Editing ? GAIKeys.ScreenNames.EditSnapshots : GAIKeys.ScreenNames.SelectSnapshot);

			CollectionView.AllowsMultipleSelection = true;

			var leftItem = selecting || Editing ? cancelButton : editButton;
			var rightItem = showActivity ? activityButton : Editing ? trashButton : selecting ? doneButton : null;

			if (NavigationItem.LeftBarButtonItem != leftItem) NavigationItem.SetLeftBarButtonItem(leftItem, animate);
			if (NavigationItem.RightBarButtonItem != rightItem) NavigationItem.SetRightBarButtonItem(rightItem, animate);

			if (reloadData) {

				if (TrapState.Shared.InActionExtension) {

					CollectionView.ReloadData();

				} else {
					
					Task.Run(async () => {
						
						var oldCount = assetsFetchResults?.Count ?? 0;

						await TrapState.Shared.GetAlbumLocalIdentifier();

						PHPhotoLibrary.SharedPhotoLibrary.UnregisterChangeObserver(this);

						assetsFetchResults = PHAsset.FetchAssets(PHAssetMediaType.Image, fetchOptions);

						if ((assetsFetchResults?.Count ?? 0) > oldCount) InvokeOnMainThread(() => CollectionView.ReloadData());

						PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);
					});
				}
			}
		}
		public void PhotoLibraryDidChange (PHChange changeInstance)
		{
			// Call might come on any background queue. Re-dispatch to the main queue to handle it.
			DispatchQueue.MainQueue.DispatchAsync (() => {
				// check if there are changes to the assets (insertions, deletions, updates)
				var collectionChanges = changeInstance.GetFetchResultChangeDetails(AssetsFetchResults);
				if (collectionChanges != null) {
					var collectionView = CollectionView;
					if (collectionView == null)
					{
						return;
					}

					// get the new fetch result
					AssetsFetchResults = collectionChanges.FetchResultAfterChanges;

					if (!collectionChanges.HasIncrementalChanges || collectionChanges.HasMoves) {
						// we need to reload all if the incremental diffs are not available
						collectionView.ReloadData();
					} else {
						// if we have incremental diffs, tell the collection view to animate insertions and deletions
						collectionView.PerformBatchUpdates(() => {
							var removedIndexes = collectionChanges.RemovedIndexes;
							if (removedIndexes != null && removedIndexes.Count > 0) {
								collectionView.DeleteItems(GetIndexesWithSection(removedIndexes, 0));
							}

							var insertedIndexes = collectionChanges.InsertedIndexes;
							if (insertedIndexes != null && insertedIndexes.Count > 0) {
								collectionView.InsertItems(GetIndexesWithSection(insertedIndexes, 0));
								if (_picker.ShowCameraButton && _picker.AutoSelectCameraImages) {
									foreach (var path in GetIndexesWithSection(insertedIndexes, 0)) {
										collectionView.Source.ItemSelected(collectionView, path);
									}
								}
							}

							var changedIndexes = collectionChanges.ChangedIndexes;
							if (changedIndexes != null && changedIndexes.Count > 0) {
								collectionView.ReloadItems(GetIndexesWithSection(changedIndexes, 0));
							}
						}, (x) => {
							if (_picker.GridSortOrder == SortOrder.Ascending)
							{
								var item = collectionView.NumberOfItemsInSection(0) - 1;
								var path = NSIndexPath.FromItemSection(item, 0);
								collectionView.ScrollToItem(path, UICollectionViewScrollPosition.Bottom, true);
							}
							else
							{
								var path = NSIndexPath.FromItemSection(0, 0);
								collectionView.ScrollToItem(path, UICollectionViewScrollPosition.Top, true);
							}
						});
					}
					ResetCachedAssets();
				}
			});
		}
		public void PhotoLibraryDidChange (PHChange changeInstance)
		{
			BeginInvokeOnMainThread(() => {

				// check if there are changes to the assets (insertions, deletions, updates)
				var collectionChanges = changeInstance.GetFetchResultChangeDetails(assetsFetchResults);

				if (collectionChanges != null) {

					assetsFetchResults = collectionChanges.FetchResultAfterChanges;

					if (!collectionChanges.HasIncrementalChanges || collectionChanges.HasMoves) {

						CollectionView.ReloadData();

					} else {
					
						var removedIndexes = indexPathsFromIndexSet(collectionChanges.RemovedIndexes);

						var insertedIndexes = indexPathsFromIndexSet(collectionChanges.InsertedIndexes);

						var changedIndexes = indexPathsFromIndexSet(collectionChanges.ChangedIndexes);

						// if we have incremental diffs, tell the collection view to animate insertions and deletions
						CollectionView.PerformBatchUpdates(() => {

							if (!removedIndexes.IsEmpty()) CollectionView.DeleteItems(removedIndexes.ToArray());

							if (!insertedIndexes.IsEmpty()) CollectionView.InsertItems(insertedIndexes.ToArray());

							if (!changedIndexes.IsEmpty()) CollectionView.ReloadItems(changedIndexes.ToArray());

						}, null);
					}
				}
			});
		}
 public void UpdateFetchResult(PHFetchResult fetchResults)
 {
     _fetchResults = fetchResults;
 }
Esempio n. 37
0
 private void OnPhotoLibraryDidChange(PHFetchResult fetchResult)
 {
     lock (_locker)
     {
         InitialiseAssets(fetchResult);
         InitialiseImages(_assets);
     }
     this.RaiseEvent(PhotoLibraryChanged, EventArgs.Empty);
 }
Esempio n. 38
0
 private void InitialiseAssets(PHFetchResult fetchResult)
 {
     _fetchResult = fetchResult;
     _assets = fetchResult.Cast<PHAsset>()
                          .Where(x => x.PixelWidth > 0 && x.PixelHeight > 0)
                          .ToDictionary(x => x.LocalIdentifier);
 }
		public void PhotoLibraryDidChange (PHChange changeInstance)
		{
			// Change notifications may be made on a background queue. Re-dispatch to the
			// main queue before acting on the change as we'll be updating the UI.
			DispatchQueue.MainQueue.DispatchSync (() => {
				// Check each of the three top-level fetches for changes.

				// Update the cached fetch result. 
				var changeDetails = changeInstance.GetFetchResultChangeDetails (allPhotos);
				if (changeDetails != null) {
					allPhotos = changeDetails.FetchResultAfterChanges;
					// (The table row for this one doesn't need updating, it always says "All Photos".)
				}

				// Update the cached fetch results, and reload the table sections to match.
				changeDetails = changeInstance.GetFetchResultChangeDetails (smartAlbums);
				if (changeDetails != null) {
					smartAlbums = changeDetails.FetchResultAfterChanges;
					TableView.ReloadSections (NSIndexSet.FromIndex ((int)Section.SmartAlbums), UITableViewRowAnimation.Automatic);
				}

				changeDetails = changeInstance.GetFetchResultChangeDetails (userCollections);
				if (changeDetails != null) {
					userCollections = changeDetails.FetchResultAfterChanges;
					TableView.ReloadSections (NSIndexSet.FromIndex ((int)Section.UserCollections), UITableViewRowAnimation.Automatic);
				}
			});
		}
 public PhotosViewController(IntPtr handle) : base(handle)
 {
     imageManager = new PHImageManager();
     Images       = PHAsset.FetchAssets(PHAssetMediaType.Image, null);
     PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(observer = new PhotoLibraryObserver(this));
 }
Esempio n. 41
0
 public void UpdateFetchResult(PHFetchResult fetchResult)
 {
     _updatedFetchResult = fetchResult;
 }