예제 #1
0
        public void SaveImageFromByte(byte[] imageByte, string fileName)
        {
            var imageData = new UIImage(NSData.FromArray(imageByte));

            PHPhotoLibrary.RequestAuthorization(status =>
            {
                switch (status)
                {
                case PHAuthorizationStatus.Restricted:
                case PHAuthorizationStatus.Denied:
                    // nope you don't have permission
                    break;

                case PHAuthorizationStatus.Authorized:

                    imageData.SaveToPhotosAlbum((image, error) =>
                    {
                        //you can retrieve the saved UI Image as well if needed using
                        //var i = image as UIImage;
                        if (error != null)
                        {
                            Console.WriteLine(error.ToString());
                        }
                    });
                    break;
                }
            });
        }
예제 #2
0
        Task <PermissionStatus> RequestPhotosPermission()
        {
            if (PhotosPermissionStatus == PermissionStatus.Granted)
            {
                return(Task.FromResult(PermissionStatus.Granted));
            }

            var tcs = new TaskCompletionSource <PermissionStatus>();

            PHPhotoLibrary.RequestAuthorization(status =>
            {
                switch (status)
                {
                case PHAuthorizationStatus.Authorized:
                    tcs.SetResult(PermissionStatus.Granted);
                    break;

                case PHAuthorizationStatus.Denied:
                    tcs.SetResult(PermissionStatus.Denied);
                    break;

                case PHAuthorizationStatus.Restricted:
                    tcs.SetResult(PermissionStatus.Restricted);
                    break;

                default:
                    tcs.SetResult(PermissionStatus.Unknown);
                    break;
                }
            });

            return(tcs.Task);
        }
예제 #3
0
        private async Task <bool> OnSaveSignature(Stream bitmap, string filename)
        {
            var tcs = new TaskCompletionSource <bool> ();

            UIImage image;

            using (var data = NSData.FromStream(bitmap))
            {
                image = UIImage.LoadFromData(data);
            }

            var status = await PHPhotoLibrary.RequestAuthorizationAsync();

            if (status == PHAuthorizationStatus.Authorized)
            {
                image.SaveToPhotosAlbum((i, error) =>
                {
                    image.Dispose();

                    tcs.TrySetResult(error == null);
                });
            }
            else
            {
                tcs.TrySetResult(false);
            }

            return(await tcs.Task);
        }
예제 #4
0
        public static void PerformChangesWithAuthorization(Action authorizedAction, Action errorAction,
                                                           Action completedAction)
        {
            PHPhotoLibrary.RequestAuthorization(status =>
            {
                if (status == PHAuthorizationStatus.Authorized)
                {
                    PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(authorizedAction, (_, error) =>
                    {
                        if (error != null)
                        {
                            Console.WriteLine(
                                $"capture session: Error occured while saving video or photo library: {error}");
                            errorAction?.Invoke();
                        }

                        completedAction?.Invoke();
                    });
                }
                else
                {
                    errorAction?.Invoke();
                }
            });
        }
예제 #5
0
        public static bool CheckForPhotoPermissionGranted(UIViewController vc)
        {
            if (vc == null)
            {
                return(false);
            }

            if (PHPhotoLibrary.AuthorizationStatus == PHAuthorizationStatus.NotDetermined)
            {
                PHPhotoLibrary.RequestAuthorization((PHAuthorizationStatus obj) =>
                {
                    if (obj != PHAuthorizationStatus.Authorized)
                    {
                        CheckForPhotoPermissionGranted(vc);
                        return;
                    }
                });
            }
            else if (PHPhotoLibrary.AuthorizationStatus != PHAuthorizationStatus.Authorized)
            {
                UIAlertController alertController = UIAlertController.Create(Strings.Basic.error, Strings.Permissions.photos_disabled, UIAlertControllerStyle.Alert);
                alertController.AddAction(UIAlertAction.Create(Strings.Basic.settings, UIAlertActionStyle.Default, delegate
                {
                    UIApplication.SharedApplication.OpenUrl(NSUrl.FromString(UIApplication.OpenSettingsUrlString));
                }));
                alertController.AddAction(UIAlertAction.Create(Strings.Basic.ok, UIAlertActionStyle.Cancel, delegate
                {
                    alertController.DismissViewController(true, null);
                }));
                vc.PresentViewController(alertController, true, null);
                return(false);
            }

            return(true);
        }
        private void SavePicture()
        {
            var image = PictureView.Image;

            PHPhotoLibrary.RequestAuthorization(status =>
            {
                switch (status)
                {
                case PHAuthorizationStatus.Denied:
                case PHAuthorizationStatus.Restricted:

                    return;

                case PHAuthorizationStatus.Authorized:
                    break;
                }
            });

            image.SaveToPhotosAlbum((UIimage, error) =>
            {
                if (error != null)
                {
                    Console.WriteLine("error:" + error);
                }
                else
                {
                    var o = UIimage as UIImage;
                }
            });
        }
예제 #7
0
        public async Task <string> PickFile()
        {
            var status = await PHPhotoLibrary.RequestAuthorizationAsync();

            if (status != PHAuthorizationStatus.Authorized)
            {
                return(null);
            }
            var taskCompletionSource = new TaskCompletionSource <string>();
            var imagePicker          = new UIImagePickerController();

            imagePicker.FinishedPickingMedia += (sender, args) => {
                taskCompletionSource.SetResult(args.ReferenceUrl?.AbsoluteString);
                imagePicker.DismissModalViewController(true);
            };
            imagePicker.Canceled += (sender, args) => {
                taskCompletionSource.SetResult(null);
                imagePicker.DismissModalViewController(true);
            };
            UIWindow window         = UIApplication.SharedApplication.KeyWindow;
            var      viewController = window.RootViewController;

            viewController.PresentModalViewController(imagePicker, true);
            return(await taskCompletionSource.Task);
        }
예제 #8
0
        //
        // This method is invoked when the application has loaded and is ready to run. In this
        // method you should instantiate the window, load the UI into it and then make the window
        // visible.
        //
        // You have 17 seconds to return from this method, or iOS will terminate your application.
        //
        public override bool FinishedLaunching(UIApplication app, NSDictionary options)
        {
            Rg.Plugins.Popup.Popup.Init();
            global::Xamarin.Forms.Forms.Init();
            LoadApplication(new App());

            PHPhotoLibrary.RequestAuthorization(status =>
            {
                switch (status)
                {
                case PHAuthorizationStatus.Authorized:
                    // Add code do run if user authorized permission, if needed.
                    break;

                case PHAuthorizationStatus.Denied:
                    // Add code do run if user denied permission, if needed.
                    break;

                case PHAuthorizationStatus.Restricted:
                    // Add code do run if user restricted permission, if needed.
                    break;

                default:
                    break;
                }
            });

            App.ScreenWidth  = (int)UIScreen.MainScreen.Bounds.Width;
            App.ScreenHeight = (int)UIScreen.MainScreen.Bounds.Height;

            return(base.FinishedLaunching(app, options));
        }
        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");
                }
            }
        }
        private async void SetGalleryButton()
        {
            var status = await PHPhotoLibrary.RequestAuthorizationAsync();

            if (status == PHAuthorizationStatus.Authorized)
            {
                var fetchedAssets    = PHAsset.FetchAssets(PHAssetMediaType.Image, null);
                var lastGalleryPhoto = fetchedAssets.LastObject 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;
            }
        }
예제 #11
0
        public Task RequestAccess()
        {
            var tcs = new TaskCompletionSource <object> ();

            PHPhotoLibrary.RequestAuthorization(_ => tcs.SetResult(null));
            return(tcs.Task);
        }
예제 #12
0
        // Requests all album and smart albums collections to be fetched.
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // TODO: https://trello.com/c/ZLOvAFWp
            PHPhotoLibrary.RequestAuthorization(status => {
                if (status != PHAuthorizationStatus.Authorized)
                {
                    return;
                }

                // Fetch all albums
                var allAlbums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.Album, PHAssetCollectionSubtype.Any, null)
                                .Cast <PHAssetCollection> ();
                albums.AddRange(allAlbums);

                // Fetch all smart albums
                var smartAlbums = PHAssetCollection.FetchAssetCollections(PHAssetCollectionType.SmartAlbum, PHAssetCollectionSubtype.Any, null)
                                  .Cast <PHAssetCollection> ();
                albums.AddRange(smartAlbums);

                // Ask the collection view to reload data, so the fetched albums is displayed.
                NSOperationQueue.MainQueue.AddOperation(() => {
                    CollectionView?.ReloadData();
                });
            });
        }
예제 #13
0
        private UIAlertAction AbrirGaleria(UIImagePickerController ImagePicker)
        {
            const String  HeaderMessage = "Se necesita acceso a la galería";
            const String  BodyMessage   = "Habilita el acceso de Worklabs a la galería en la configuración de tu iPhone";
            UIAlertAction openGalery    = UIAlertAction.Create("Selecciona una foto", UIAlertActionStyle.Default, (action) =>
            {
                var photos = PHPhotoLibrary.AuthorizationStatus;
                if (photos != PHAuthorizationStatus.NotDetermined)
                {
                    this.PresentViewController(this.SelectImage(ImagePicker), true, null);
                }
                else
                {
                    PHPhotoLibrary.RequestAuthorization(handler: (obj) =>
                    {
                        InvokeOnMainThread(() =>
                        {
                            if (obj != PHAuthorizationStatus.Authorized)
                            {
                                this.PresentViewController(this.PermisosDispositivo(HeaderMessage, BodyMessage), true, null);
                            }
                            else
                            {
                                this.PresentViewController(this.SelectImage(ImagePicker), true, null);
                            }
                        });
                    });
                }
            });

            return(openGalery);
        }
예제 #14
0
        async partial void SaveImageClicked(UIButton sender)
        {
            UIImage image;

            using (var bitmap = await signatureView.GetImageStreamAsync(SignatureImageFormat.Png, UIColor.Black, UIColor.White, 1f))
                using (var data = NSData.FromStream(bitmap))
                {
                    image = UIImage.LoadFromData(data);
                }

            var status = await PHPhotoLibrary.RequestAuthorizationAsync();

            if (status == PHAuthorizationStatus.Authorized)
            {
                image.SaveToPhotosAlbum((i, error) =>
                {
                    image.Dispose();

                    if (error == null)
                    {
                        ShowToast("Raster signature saved to the photo library.");
                    }
                    else
                    {
                        ShowToast("There was an error saving the signature: " + error.LocalizedDescription);
                    }
                });
            }
            else
            {
                ShowToast("Permission to save to the photo library was denied.");
            }
        }
        async void RequestAccessToPhotoLibrary()
        {
            switch (PHPhotoLibrary.AuthorizationStatus)
            {
            case PHAuthorizationStatus.NotDetermined:
                await PHPhotoLibrary.RequestAuthorizationAsync();

                GetPhotos();
                break;

            case PHAuthorizationStatus.Authorized:
                break;

            default:
                UIAlertHelper.ShowMessage("Cannot access to Photo Library!",
                                          "Please, check in Settings app that you have permission to access to Photos.",
                                          NavigationController,
                                          "Ok",
                                          null,
                                          null,
                                          null,
                                          new [] { "Go to settings" },
                                          new Action[] { OpenSettings });
                break;
            }
        }
예제 #16
0
        /// Reload collection view layout/data based on authorization status of photo library
        private void ReloadData(PHAuthorizationStatus status)
        {
            switch (status)
            {
            case PHAuthorizationStatus.Authorized:
                _collectionViewDataSource.AssetsModel.UpdateFetchResult(AssetsFetchResultBlock?.Invoke());
                _collectionViewDataSource.UpdateLayoutModel(new LayoutModel(LayoutConfiguration,
                                                                            (int)_collectionViewDataSource.AssetsModel.FetchResult.Count));
                break;

            case PHAuthorizationStatus.Restricted:
            case PHAuthorizationStatus.Denied:
                var view = _overlayView ?? DataSource?.ImagePicker(status);
                if (view != null && !view.Superview.Equals(CollectionView))
                {
                    CollectionView.BackgroundView = view;
                    _overlayView = view;
                }

                break;

            case PHAuthorizationStatus.NotDetermined:
                PHPhotoLibrary.RequestAuthorization(authorizationStatus =>
                {
                    DispatchQueue.MainQueue.DispatchAsync(() => { ReloadData(authorizationStatus); });
                });
                break;
            }
        }
 partial void pressSelectImage(UIButton sender)
 {
     if (PHPhotoLibrary.AuthorizationStatus == PHAuthorizationStatus.NotDetermined)
     {
         PHPhotoLibrary.RequestAuthorization((PHAuthorizationStatus status) =>
         {
             if (status == PHAuthorizationStatus.Authorized)
             {
                 DispatchQueue.MainQueue.DispatchAsync(() =>
                 {
                     OpenImagePickerController();
                 });
             }
             else
             {
                 SharedService.ShowErrorDialog("無權限開啟相簿,請至設定內修改隱私權限", this);
             }
         });
     }
     else if (PHPhotoLibrary.AuthorizationStatus == PHAuthorizationStatus.Authorized)
     {
         OpenImagePickerController();
     }
     else
     {
         SharedService.ShowErrorDialog("無權限開啟相簿,請至設定內修改隱私權限", this);
     }
 }
        void CheckPhotoLibraryAutorizationStatus(PHAuthorizationStatus authorizationStatus)
        {
            switch (authorizationStatus)
            {
            case PHAuthorizationStatus.NotDetermined:
                PHPhotoLibrary.RequestAuthorization(CheckPhotoLibraryAutorizationStatus);
                break;

            case PHAuthorizationStatus.Restricted:
                InvokeOnMainThread(() => ShowMessage("Acceso Restringido", "", NavigationController));
                break;

            case PHAuthorizationStatus.Denied:
                InvokeOnMainThread(() => ShowMessage("Acceso Denegado", "", NavigationController));

                break;

            case PHAuthorizationStatus.Authorized:
                InvokeOnMainThread(() =>
                {
                    var imagePickerController = new UIImagePickerController
                    {
                        SourceType = UIImagePickerControllerSourceType.PhotoLibrary,
                        Delegate   = this
                    };
                    PresentViewController(imagePickerController, true, null);
                });


                break;

            default:
                break;
            }
        }
        /// <summary>
        /// Opens the photo library to allow the user to choose a picture.
        /// </summary>
        /// <param name="parent">The parent view controller that invoked the method.</param>
        /// <param name="callback">The function to call after a picture was chosen.</param>
        public static void SelectPicture <TViewModel>(BaseViewController <TViewModel> parent, Action <NSDictionary> callback, Action onCancel)
            where TViewModel : BaseViewModel
        {
            var status = PHPhotoLibrary.AuthorizationStatus;

            if (status == PHAuthorizationStatus.NotDetermined)
            {
                PHPhotoLibrary.RequestAuthorization((PHAuthorizationStatus authStatus) =>
                {
                    if (authStatus == PHAuthorizationStatus.Authorized)
                    {
                        // Show the media picker.
                        parent.InvokeOnMainThread(delegate
                        {
                            InitializePhotoPicker(parent, callback, onCancel);
                        });
                    }
                    // If they have said no do nothing.
                });
            }
            else if (status == PHAuthorizationStatus.Authorized)
            {
                // Show the media picker.
                InitializePhotoPicker(parent, callback, onCancel);
            }
            else
            {
                // They said no in the past, so show them an alert to direct them to the app's settings.
                OpenSettingsAlert(parent, "Photo Access Required", "Authorization to access photos is required to use this feature of the app.");
            }
        }
        /// <summary>Checks the status of <see cref="SaveMediaPermission"/>.</summary>
        /// <returns>The current status of the permission.</returns>
        public override Task <PermissionStatus> CheckStatusAsync()
        {
            EnsureDeclared();
            var auth = MediaGallery.HasOSVersion(14)
                ? PHPhotoLibrary.GetAuthorizationStatus(PHAccessLevel.AddOnly)
                : PHPhotoLibrary.AuthorizationStatus;

            return(Task.FromResult(Convert(auth)));
        }
예제 #21
0
        protected override async Task StartListeningAsync()
        {
            await base.StartListeningAsync();

            if (await PHPhotoLibrary.RequestAuthorizationAsync() == PHAuthorizationStatus.Authorized)
            {
                PHPhotoLibrary.SharedPhotoLibrary.RegisterChangeObserver(_changeObserver);
            }
        }
예제 #22
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);
                    }
                });
            });
        }
        public override void DidFinishCapture(AVCapturePhotoOutput captureOutput, AVCaptureResolvedPhotoSettings resolvedSettings, NSError error)
        {
            if (error != null)
            {
                Console.WriteLine($"Error capturing photo: {error.LocalizedDescription})");
                DidFinish();
                return;
            }

            if (photoData == null)
            {
                Console.WriteLine("No photo data resource");
                DidFinish();
                return;
            }

            PHPhotoLibrary.RequestAuthorization(status =>
            {
                if (status == PHAuthorizationStatus.Authorized)
                {
                    PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
                    {
                        var options = new PHAssetResourceCreationOptions
                        {
                            UniformTypeIdentifier = RequestedPhotoSettings.ProcessedFileType,
                        };

                        var creationRequest = PHAssetCreationRequest.CreationRequestForAsset();
                        creationRequest.AddResource(PHAssetResourceType.Photo, photoData, options);

                        var url = livePhotoCompanionMovieUrl;
                        if (url != null)
                        {
                            var livePhotoCompanionMovieFileResourceOptions = new PHAssetResourceCreationOptions
                            {
                                ShouldMoveFile = true
                            };
                            creationRequest.AddResource(PHAssetResourceType.PairedVideo, url, livePhotoCompanionMovieFileResourceOptions);
                        }
                    }, (success, err) =>
                    {
                        if (err != null)
                        {
                            Console.WriteLine($"Error occurered while saving photo to photo library: {error.LocalizedDescription}");
                        }
                        DidFinish();
                    });
                }
                else
                {
                    DidFinish();
                }
            });
        }
예제 #24
0
        public async Task <bool> RequestAuthorizationAsync()
        {
            if (IsAuthorized())
            {
                return(true);
            }

            var status = await PHPhotoLibrary.RequestAuthorizationAsync();

            return(status == PHAuthorizationStatus.Authorized);
        }
예제 #25
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            PHPhotoLibrary.RequestAuthorization((status) =>
            {
                if (status == PHAuthorizationStatus.Authorized)
                {
                    DispatchQueue.MainQueue.DispatchAsync(() => this.LoadAssetsFromLibrary());
                }
            });
        }
예제 #26
0
        private async Task <bool> Import()
        {
            var status = await PHPhotoLibrary.RequestAuthorizationAsync();

            if (status != PHAuthorizationStatus.Authorized)
            {
                return(false);
            }
            results = PHAsset.FetchAssets(PHAssetMediaType.Image, null).Select(x => (PHAsset)x).ToArray();

            return(true);
        }
        public async Task <bool> RequestPermissionAsync()
        {
            var status = PHPhotoLibrary.AuthorizationStatus;

            bool authotization = status == PHAuthorizationStatus.Authorized;

            if (!authotization)
            {
                authotization = await PHPhotoLibrary.RequestAuthorizationAsync() == PHAuthorizationStatus.Authorized;
            }
            return(authotization);
        }
예제 #28
0
        // キャプチャー後処理
        public override void DidFinishCapture(AVCapturePhotoOutput captureOutput, AVCaptureResolvedPhotoSettings resolvedSettings, NSError error)
        {
            if (error != null)
            {
                Console.WriteLine($"Error capturing photo: {error.LocalizedDescription})");
                return;
            }

            if (photoData == null)
            {
                Console.WriteLine("No photo data resource");
                return;
            }

            // 撮影したラベル画像をフォトアルバムに保存するか
            // フォトアルバムに保存する必要が出てきた真偽値をTrueにする
            bool IsSaveToPhotoAlbum = false;

            // 画像を保存するかどうかの判定
            if (IsSaveToPhotoAlbum)
            {
                // 撮影した画像を保存する処理
                PHPhotoLibrary.RequestAuthorization(status =>
                {
                    if (status == PHAuthorizationStatus.Authorized)
                    {
                        PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() =>
                        {
                            var creationRequest = PHAssetCreationRequest.CreationRequestForAsset();
                            creationRequest.AddResource(PHAssetResourceType.Photo, photoData, null);

                            var url = livePhotoCompanionMovieUrl;
                            if (url != null)
                            {
                                var livePhotoCompanionMovieFileResourceOptions = new PHAssetResourceCreationOptions
                                {
                                    ShouldMoveFile = true
                                };
                                creationRequest.AddResource(PHAssetResourceType.PairedVideo, url, livePhotoCompanionMovieFileResourceOptions);
                            }
                        }, (success, err) =>
                        {
                            if (err != null)
                            {
                                Console.WriteLine($"Error occurered while saving photo to photo library: {error.LocalizedDescription}");
                            }
                        });
                    }
                });
            }
        }
예제 #29
0
        private void PresentButtonTapped(object sender, EventArgs e)
        {
            _presentButton.Selected = !_presentButton.Selected;

            if (!_presentButton.Selected)
            {
                UpdateNavigationItem(0);
                _imagePicker.Release();
                _currentInputView = null;
                ReloadInputViews();
                return;
            }

            _imagePicker = _imagePickerConfigurationHandlerClass.CreateImagePicker();


            _imagePickerController = new ImagePickerControllerDelegate()
            {
                DidSelectActionItemAction = DidSelectActionItemAt,
                DidDeselectAssetAction    = UpdateSelectedItems,
                DidSelectAssetAction      = UpdateSelectedItems
            };

            _imagePicker.Delegate   = _imagePickerController;
            _imagePicker.DataSource = _imagePickerControllerDataSource;

            // presentation
            // before we present VC we can ask for authorization to photo library,
            // if we don't do it now, Image Picker will ask for it automatically
            // after it's presented.
            PHPhotoLibrary.RequestAuthorization(handler =>
            {
                DispatchQueue.MainQueue.DispatchAsync(() =>
                {
                    // we can present VC regardless of status because we support
                    // non granted states in Image Picker. Please check `ImagePickerControllerDataSource`
                    // for more info.
                    if (_imagePickerConfigurationHandlerClass.PresentsModally)
                    {
                        _imagePicker.LayoutConfiguration.ScrollDirection = UICollectionViewScrollDirection.Vertical;
                        PresentPickerModally(_imagePicker);
                    }
                    else
                    {
                        _imagePicker.LayoutConfiguration.ScrollDirection =
                            UICollectionViewScrollDirection.Horizontal;
                        PresentPickerAsInputView(_imagePicker);
                    }
                });
            });
        }
예제 #30
0
        private async Task ValidatePhotoLibraryAccess()
        {
            if (!IsUsageKeyDefined("NSPhotoLibraryUsageDescription"))
            {
                throw new InvalidOperationException("Info.plist must define NSPhotoLibraryUsageDescription");
            }

            var isAllowed = (await PHPhotoLibrary.RequestAuthorizationAsync()) == PHAuthorizationStatus.Authorized;

            if (!isAllowed)
            {
                throw new UnauthorizedAccessException();
            }
        }