public override void AwakeFromNib ()
		{
			imageManager = new PHCachingImageManager ();
			ResetCachedAssets ();

			PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver (this);
		}
Esempio n. 2
0
        public sealed override async void ViewDidLoad()
        {
            try
            {
                base.ViewDidLoad();

                SetupViews();

                if (!string.IsNullOrEmpty(_picker.CustomNavigationBarPrompt))
                {
                    NavigationItem.Prompt = _picker.CustomNavigationBarPrompt;
                }

                _imageManager = new PHCachingImageManager();
                ResetCachedAssets();

                // Register for changes
                PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);

                _viewDidLoadAsyncTask = ViewDidLoadAsync();
                await _viewDidLoadAsyncTask;
            }
            catch (Exception ex)
            {
                //Handle
            }
        }
        public override void AwakeFromNib()
        {
            imageManager = new PHCachingImageManager();
            ResetCachedAssets();

            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);
        }
Esempio n. 4
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			SetupViews ();

			if (!string.IsNullOrEmpty(_picker.CustomNavigationBarPrompt)) {
				NavigationItem.Prompt = _picker.CustomNavigationBarPrompt;
			}

			_imageManager = new PHCachingImageManager ();
			ResetCachedAssets ();

			// Register for changes
			PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver (this);
		}
Esempio n. 5
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            SetupViews();

            if (!string.IsNullOrEmpty(_picker.CustomNavigationBarPrompt))
            {
                NavigationItem.Prompt = _picker.CustomNavigationBarPrompt;
            }

            _imageManager = new PHCachingImageManager();
            ResetCachedAssets();

            // Register for changes
            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);

            if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0))
            {
                EdgesForExtendedLayout = UIRectEdge.None;
            }
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad ();

            PHPhotoLibrary.RequestAuthorization ((status) => {
                if(status == PHAuthorizationStatus.Authorized)
                {
                    var result = PHAssetCollection.FetchTopLevelUserCollections(null);

                    var assetCollection = result.firstObject as PHAssetCollection;

                    var imageManager = new PHCachingImageManager();

                    var assets = PHAsset.FetchAssets(assetCollection, null);

                    var imageAsset = assets[6];

                    this.InvokeOnMainThread(() => {
                        imageManager.RequestImageForAsset((PHAsset)imageAsset, this.View.Frame.Size, PHImageContentMode.Default, null, new PHImageResultHandler(this.ImageReceived));
                    });
                }
            });
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            PHPhotoLibrary.RequestAuthorization((status) => {
                if (status == PHAuthorizationStatus.Authorized)
                {
                    var result = PHAssetCollection.FetchTopLevelUserCollections(null);

                    var assetCollection = result.firstObject as PHAssetCollection;

                    var imageManager = new PHCachingImageManager();

                    var assets = PHAsset.FetchAssets(assetCollection, null);

                    var imageAsset = assets[6];

                    this.InvokeOnMainThread(() => {
                        imageManager.RequestImageForAsset((PHAsset)imageAsset, this.View.Frame.Size, PHImageContentMode.Default, null, new PHImageResultHandler(this.ImageReceived));
                    });
                }
            });
        }
Esempio n. 8
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. 9
0
		public ImageModel(PHAsset asset, PHCachingImageManager manager)
		{
			ImageAsset = asset;
			ImageManager = manager;
		}
Esempio n. 10
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            _picker = (GMImagePickerController)NavigationController.ParentViewController;
            View.BackgroundColor = _picker.PickerBackgroundColor;

            // Navigation bar customization
            if (!string.IsNullOrWhiteSpace(_picker.CustomNavigationBarPrompt))
            {
                NavigationItem.Prompt = _picker.CustomNavigationBarPrompt;
            }

            _imageManager = new PHCachingImageManager();

            // Table view aspect
            TableView.RowHeight      = AlbumRowHeight;
            TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
            TableView.Source         = new GMAlbumsViewTableViewSource(this);

            // Buttons
            var barButtonItemAttributes = new UITextAttributes
            {
                Font = UIFont.FromName(_picker.PickerFontName, _picker.PickerFontHeaderSize)
            };

            var cancelTitle = _picker.CustomCancelButtonTitle ?? "picker.navigation.cancel-button".Translate(defaultValue: "Cancel");

            NavigationItem.LeftBarButtonItem = new UIBarButtonItem(cancelTitle,
                                                                   UIBarButtonItemStyle.Plain,
                                                                   Dismiss);

            if (_picker.UseCustomFontForNavigationBar)
            {
                NavigationItem.LeftBarButtonItem.SetTitleTextAttributes(barButtonItemAttributes, UIControlState.Normal);
                NavigationItem.LeftBarButtonItem.SetTitleTextAttributes(barButtonItemAttributes, UIControlState.Highlighted);
            }

            if (_picker.AllowsMultipleSelection)
            {
                var doneTitle = _picker.CustomDoneButtonTitle ?? "picker.navigation.done-button".Translate(defaultValue: "Done");
                NavigationItem.RightBarButtonItem = new UIBarButtonItem(doneTitle,
                                                                        UIBarButtonItemStyle.Done,
                                                                        FinishPickingAssets);
                if (_picker.UseCustomFontForNavigationBar)
                {
                    NavigationItem.RightBarButtonItem.SetTitleTextAttributes(barButtonItemAttributes, UIControlState.Normal);
                    NavigationItem.RightBarButtonItem.SetTitleTextAttributes(barButtonItemAttributes, UIControlState.Highlighted);
                }
                NavigationItem.RightBarButtonItem.Enabled = !_picker.AutoDisableDoneButton || _picker.SelectedAssets.Any();
            }

            // Bottom toolbar
            ToolbarItems = _picker.GetToolbarItems();

            // Title
            Title = _picker.Title ?? "picker.navigation.title".Translate(defaultValue: "Navigation bar default title");

            // Fetch PHAssetCollections
            var topLevelUserCollections = PHCollection.FetchTopLevelUserCollections(null);
            var smartAlbums             = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.AlbumRegular, null);

            _collectionsFetchResults = new List <PHFetchResult> {
                topLevelUserCollections, smartAlbums
            };
            _collectionsLocalizedTitles = new List <string> {
                "picker.table.user-albums-header".Translate(defaultValue: "Albums"), "picker.table.smart-albums-header".Translate("Smart Albums")
            };

            UpdateFetchResults();

            // Register for changes
            PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);
        }
        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 override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			_picker = (GMImagePickerController) NavigationController.ParentViewController;
			View.BackgroundColor = _picker.PickerBackgroundColor;

			// Navigation bar customization
			if (!string.IsNullOrWhiteSpace (_picker.CustomNavigationBarPrompt)) {
				NavigationItem.Prompt = _picker.CustomNavigationBarPrompt;
			}

			_imageManager = new PHCachingImageManager ();

			// Table view aspect
			TableView.RowHeight = AlbumRowHeight;
			TableView.SeparatorStyle = UITableViewCellSeparatorStyle.None;
			TableView.Source = new GMAlbumsViewTableViewSource (this);

			// Buttons
			var barButtonItemAttributes = new UITextAttributes {
				Font = UIFont.FromName(_picker.PickerFontName, _picker.PickerFontHeaderSize)
			};
					
			var cancelTitle = _picker.CustomCancelButtonTitle ?? "picker.navigation.cancel-button".Translate(defaultValue: "Cancel");
			NavigationItem.LeftBarButtonItem = new UIBarButtonItem (cancelTitle,
				UIBarButtonItemStyle.Plain,
				Dismiss);

			if (_picker.UseCustomFontForNavigationBar) {
				NavigationItem.LeftBarButtonItem.SetTitleTextAttributes(barButtonItemAttributes, UIControlState.Normal);
				NavigationItem.LeftBarButtonItem.SetTitleTextAttributes(barButtonItemAttributes, UIControlState.Highlighted);
			}

			if (_picker.AllowsMultipleSelection) {
				var doneTitle = _picker.CustomDoneButtonTitle ?? "picker.navigation.done-button".Translate(defaultValue: "Done");
				NavigationItem.RightBarButtonItem = new UIBarButtonItem (doneTitle,
					UIBarButtonItemStyle.Done,
					FinishPickingAssets);
				if (_picker.UseCustomFontForNavigationBar) {
					NavigationItem.RightBarButtonItem.SetTitleTextAttributes(barButtonItemAttributes, UIControlState.Normal);
					NavigationItem.RightBarButtonItem.SetTitleTextAttributes(barButtonItemAttributes, UIControlState.Highlighted);
				}
				NavigationItem.RightBarButtonItem.Enabled = _picker.AutoDisableDoneButton ? _picker.SelectedAssets.Any () : true;
			}

			// Bottom toolbar
			ToolbarItems = _picker.GetToolbarItems();

			// Title
			Title = _picker.Title ?? "picker.navigation.title".Translate(defaultValue: "Navigation bar default title");

			// Fetch PHAssetCollections
			var topLevelUserCollections = PHCollectionList.FetchTopLevelUserCollections(null);
			var smartAlbums = PHAssetCollection.FetchAssetCollections (PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.AlbumRegular, null);
			_collectionsFetchResults = new List<PHFetchResult> { topLevelUserCollections, smartAlbums };
			_collectionsLocalizedTitles = new List<string> { "picker.table.user-albums-header".Translate (defaultValue: "Albums"), "picker.table.smart-albums-header".Translate("Smart Albums") };

			UpdateFetchResults ();

			// Register for changes
			PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(this);

			if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0)) {
				EdgesForExtendedLayout = UIRectEdge.None;
			}
		}
Esempio n. 13
0
 public ImagePickerAssetModel()
 {
     ImageManager = new PHCachingImageManager();
 }
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			SetupViews ();

			if (!string.IsNullOrEmpty(_picker.CustomNavigationBarPrompt)) {
				NavigationItem.Prompt = _picker.CustomNavigationBarPrompt;
			}

			_imageManager = new PHCachingImageManager ();
			ResetCachedAssets ();

			// Register for changes
			PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver (this);

			if (UIDevice.CurrentDevice.CheckSystemVersion (7, 0)) {
				EdgesForExtendedLayout = UIRectEdge.None;
			}
		}
Esempio n. 15
0
 public ImageModel(PHAsset asset, PHCachingImageManager manager)
 {
     ImageAsset   = asset;
     ImageManager = manager;
 }
Esempio n. 16
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);
        }