// キャプチャー後処理 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}"); } }); } }); } }
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); } }); }); }
/// <summary> /// Check whether we are authorized to use the Photo Library /// </summary> /// <param name="onAuthorized">Callback <see cref="Action"/> which triggers when we are authorized</param> public void CheckPhotoAuthorization(Action onAuthorized) { PHPhotoLibrary.RequestAuthorization(status => { switch (status) { case PHAuthorizationStatus.Restricted: case PHAuthorizationStatus.Denied: CameraRollUnauthorized?.Invoke(this, EventArgs.Empty); break; case PHAuthorizationStatus.Authorized: onAuthorized?.Invoke(); break; } }); }
private void OnExportCompleted(AVAssetExportSession session) { this.exportProgressView.Hidden = true; this.currentTimeLabel.Hidden = false; var outputURL = session.OutputUrl; this.progressTimer.Invalidate(); this.progressTimer.Dispose(); this.progressTimer = null; if (session.Status != AVAssetExportSessionStatus.Completed) { Console.WriteLine($"exportSession error:{session.Error}"); this.ReportError(session.Error); } else { this.exportProgressView.Progress = 1f; // Save the exported movie to the camera roll PHPhotoLibrary.RequestAuthorization((status) => { if (status == PHAuthorizationStatus.Authorized) { PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => PHAssetChangeRequest.FromVideo(outputURL), (successfully, error) => { if (error != null) { Console.WriteLine($"writeVideoToAssestsLibrary failed: {error}"); this.ReportError(error); } base.InvokeOnMainThread(() => { this.playPauseButton.Enabled = true; this.transitionButton.Enabled = true; this.scrubber.Enabled = true; this.exportButton.Enabled = true; }); }); } }); } }
public 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 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}"); } DidFinish(); }); } else { DidFinish(); } }); }
void CheckPhotoLibraryAuthorizationStatus(PHAuthorizationStatus authorizationStatus) { switch (authorizationStatus) { case PHAuthorizationStatus.NotDetermined: //TODO: Ask for permission to open galerry PHPhotoLibrary.RequestAuthorization(CheckPhotoLibraryAuthorizationStatus); break; case PHAuthorizationStatus.Restricted: //TODO: Display a message of restricted InvokeOnMainThread(() => { ShowMessage("Resource not available", "The resource is not available due it's restricted to use", NavigationController); }); break; case PHAuthorizationStatus.Denied: //TODO: Show a message that user denied the authorization InvokeOnMainThread(() => { ShowMessage("Resource not available", "The resource is not available due it was denied by the user.", NavigationController); }); break; case PHAuthorizationStatus.Authorized: //TODO: Open Gallery InvokeOnMainThread(() => { var imagePickerController = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, Delegate = this }; PresentViewController(imagePickerController, true, null); }); break; default: break; } }
void CheckPhotoLibraryAuthorizationStatus(PHAuthorizationStatus authorizationStatus) { switch (authorizationStatus) { case PHAuthorizationStatus.NotDetermined: //permiso para abrir la camara PHPhotoLibrary.RequestAuthorization(CheckPhotoLibraryAuthorizationStatus); break; case PHAuthorizationStatus.Restricted: //mensaje de restringido InvokeOnMainThread(() => { ShowMessage("Recurso no disponible", "La app no tiene permiso para acceder al recurso", NavigationController); }); break; case PHAuthorizationStatus.Denied: //el usuario denego el recurso InvokeOnMainThread(() => { ShowMessage("Recurso no disponible", "El usuario denego el recurso", NavigationController); }); break; case PHAuthorizationStatus.Authorized: //Abrir galeria InvokeOnMainThread(() => { var imagePickerController = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, Delegate = this }; PresentViewController(imagePickerController, true, null); }); break; default: break; } }
private void GetFromMemory() { PHAuthorizationStatus photos = PHPhotoLibrary.AuthorizationStatus; if (photos == PHAuthorizationStatus.Authorized) { GetPhoto(); return; } PHPhotoLibrary.RequestAuthorization(status => { if (status == PHAuthorizationStatus.Authorized) { GetPhoto(); } }); }
void CheckPhotoLibraryAuthorizationStatus(PHAuthorizationStatus authorizationStatus) { switch (authorizationStatus) { case PHAuthorizationStatus.NotDetermined: // Vamos a pedir permiso para acceder a la galeria //InvokeOnMainThread(() => { PHPhotoLibrary.RequestAuthorization(CheckPhotoLibraryAuthorizationStatus); //}); break; case PHAuthorizationStatus.Restricted: InvokeOnMainThread(() => { showMessage("No disponible", "El recurso no esta disponible, esta restringido", NavigationController); }); //Mostrar mensaje de restringido break; case PHAuthorizationStatus.Denied: InvokeOnMainThread(() => { showMessage("No disponible", "El recurso no esta disponible, esta denegado por ti", NavigationController); }); //Mostrar un mensaje diciendo que el usuario denego break; case PHAuthorizationStatus.Authorized: InvokeOnMainThread(() => { var imagePickerController = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, Delegate = this }; PresentViewController(imagePickerController, true, null); }); break; default: break; } }
static void Authorize() { PHPhotoLibrary.RequestAuthorization(status => { switch (status) { case PHAuthorizationStatus.Authorized: break; case PHAuthorizationStatus.Denied: break; case PHAuthorizationStatus.Restricted: break; default: break; } }); }
private static void RequestPhotoLibrary() { var status = PHPhotoLibrary.AuthorizationStatus; if (status != PHAuthorizationStatus.NotDetermined) { RaiseAuthorizationRequested(AuthorizationType.PhotoLibrary, status.ToShared()); return; } if (_requests.TryGetValue(AuthorizationType.PhotoLibrary, out var value)) { var result = _requests.TryUpdate(AuthorizationType.PhotoLibrary, value + 1, value); } else { _requests.TryAdd(AuthorizationType.PhotoLibrary, 1); PHPhotoLibrary.RequestAuthorization(OnPhotoLibraryRequested); } }
void CheckPhotoLibraryAuthorizationStatus(PHAuthorizationStatus authorizationStatus) { switch (authorizationStatus) { case PHAuthorizationStatus.NotDetermined: //Pedir permiso PHPhotoLibrary.RequestAuthorization(CheckPhotoLibraryAuthorizationStatus); break; case PHAuthorizationStatus.Restricted: InvokeOnMainThread(() => { ShowMessage("Its is resticted", "", NavigationController); }); break; case PHAuthorizationStatus.Denied: InvokeOnMainThread(() => { ShowMessage("It is denied", "", NavigationController); }); break; case PHAuthorizationStatus.Authorized: //Open photo library InvokeOnMainThread(() => { var imagePicker = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, Delegate = this }; PresentViewController(imagePicker, true, null); }); break; default: break; } }
void CheckPhotoLibraryAutorizationStatus(PHAuthorizationStatus authorizationStatus) { switch (authorizationStatus) { case PHAuthorizationStatus.NotDetermined: //TODO: VAMOS A PEDIR EL PERMISO PARA ACCEDER LA GALERIA PHPhotoLibrary.RequestAuthorization(CheckPhotoLibraryAutorizationStatus); break; case PHAuthorizationStatus.Restricted: //TODO: MOSTRAR UN MSG DICIENDO QUE ESTA RESTRINGIDO InvokeOnMainThread(() => ShowMessage("Acceso a Fotos Restringido", "Chale weee no que si la querias ver krnal??? Te quieres morir??", NavigationController)); break; case PHAuthorizationStatus.Denied: //TODO: MOSTRAR UN MSG DICIENDO QUE ESTA DENEGADO InvokeOnMainThread(() => ShowMessage("Acceso a Fotos Denegado", "Por que no muestras los packs??? Te quieres morir??", NavigationController)); break; case PHAuthorizationStatus.Authorized: //TODO: VAMOS A ABRIR LA GALERIA InvokeOnMainThread(() => { var imagePickerController = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, Delegate = this }; PresentViewController(imagePickerController, true, null); }); break; default: break; } }
void CheckPhotoLibraryAuthorizationsStatus(PHAuthorizationStatus authorizationStatus) { switch (authorizationStatus) { case PHAuthorizationStatus.NotDetermined: // TODO: Pedir permiso para acceder PHPhotoLibrary.RequestAuthorization(CheckPhotoLibraryAuthorizationsStatus); break; case PHAuthorizationStatus.Restricted: // TODO: Mostrar un mensaje diciendo que está restringido InvokeOnMainThread(() => { ShowMessage("Error", "El recuerso no esa dispiie", NavigationController); }); break; case PHAuthorizationStatus.Denied: // TODO: Mostrar un mensaje diciendo que el usuario denego InvokeOnMainThread(() => { ShowMessage("Error", "El recuerso no esta disponible", NavigationController); }); break; case PHAuthorizationStatus.Authorized: InvokeOnMainThread(() => { var imagePickerController = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, Delegate = this }; PresentViewController(imagePickerController, true, null); }); break; default: break; } }
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)); }); } }); }
// This is the main entry point of the application. static void Main(string[] args) { PHPhotoLibrary.RequestAuthorization(status => { switch (status) { case PHAuthorizationStatus.Authorized: break; case PHAuthorizationStatus.Denied: break; case PHAuthorizationStatus.Restricted: break; default: break; } }); // if you want to use a different Application Delegate class from "AppDelegate" // you can specify it here. UIApplication.Main(args, null, "AppDelegate"); }
private void CheckPhotoLibraryAuthorizationStatus(PHAuthorizationStatus authorizationStatus) { switch (authorizationStatus) { case PHAuthorizationStatus.NotDetermined: // Vamos a pedir permiso para acceder a la galeria PHPhotoLibrary.RequestAuthorization(CheckPhotoLibraryAuthorizationStatus); break; case PHAuthorizationStatus.Restricted: InvokeOnMainThread(() => { showMessage("Not Available", "The resource is not available, it is restricted", NavigationController); }); //Mostrar mensaje de restringido break; case PHAuthorizationStatus.Denied: InvokeOnMainThread(() => { showMessage("Not Available", "The resource is not available, it is denied by you", NavigationController); }); //Mostrar un mensaje diciendo que el usuario denego break; case PHAuthorizationStatus.Authorized: InvokeOnMainThread(() => { var imagePickerController = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, Delegate = this }; PresentViewController(imagePickerController, true, null); }); break; default: break; } }
public static Task <bool> CheckPhotoPermission() { var tcs = new TaskCompletionSource <bool>(); var status = PHPhotoLibrary.AuthorizationStatus; switch (status) { case PHAuthorizationStatus.Authorized: tcs.SetResult(true); break; case PHAuthorizationStatus.Denied: case PHAuthorizationStatus.Restricted: tcs.SetResult(false); break; case PHAuthorizationStatus.NotDetermined: PHPhotoLibrary.RequestAuthorization(newStatus => { switch (newStatus) { case PHAuthorizationStatus.Authorized: tcs.SetResult(true); break; case PHAuthorizationStatus.Denied: case PHAuthorizationStatus.Restricted: default: tcs.SetResult(false); break; } }); break; } return(tcs.Task); }
void CheckLibraryAuthorizationStatus(PHAuthorizationStatus authorizationStatus) { switch (authorizationStatus) { case PHAuthorizationStatus.NotDetermined: //TODO: Vamos a pedir el permiso para acceder PHPhotoLibrary.RequestAuthorization(CheckLibraryAuthorizationStatus); break; case PHAuthorizationStatus.Restricted: //TODO: Mostrar un mensaje diciendo que esta restringido InvokeOnMainThread(() => ShowMessage("Error", "El permiso esta restringido.", NavigationController)); break; case PHAuthorizationStatus.Denied: //TODO: El usuario denego el permiso. InvokeOnMainThread(() => ShowMessage("Error", "El permiso fue denegado.", NavigationController)); break; case PHAuthorizationStatus.Authorized: //TODO: Abrir la galeria InvokeOnMainThread(() => { var imagePickerController = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, Delegate = this }; PresentViewController(imagePickerController, true, null); }); break; default: break; } }
protected override void RequestAccess() { PHPhotoLibrary.RequestAuthorization(_ => UpdateStatus()); }
public void FinishedRecording(AVCaptureFileOutput captureOutput, NSUrl outputFileUrl, NSObject[] connections, NSError error) { /* * Note that currentBackgroundRecordingID is used to end the background task * associated with this recording. This allows a new recording to be started, * associated with a new UIBackgroundTaskIdentifier, once the movie file output's * `recording` property is back to NO — which happens sometime after this method * returns. * * Note: Since we use a unique file path for each recording, a new recording will * not overwrite a recording currently being saved. */ var currentBackgroundRecordingId = backgroundRecordingId; backgroundRecordingId = UIApplication.BackgroundTaskInvalid; Action cleanup = () => { if (NSFileManager.DefaultManager.FileExists(outputFileUrl.Path)) { NSError tError; NSFileManager.DefaultManager.Remove(outputFileUrl.Path, out tError); } if (currentBackgroundRecordingId != UIApplication.BackgroundTaskInvalid) { UIApplication.SharedApplication.EndBackgroundTask(currentBackgroundRecordingId); } }; var success = true; if (error != null) { Console.WriteLine($"Movie file finishing error: {error}"); var tmpObj = error.UserInfo[AVErrorKeys.RecordingSuccessfullyFinished]; if (tmpObj is NSNumber) { success = ((NSNumber)tmpObj).BoolValue; } else if (tmpObj is NSString) { success = ((NSString)tmpObj).BoolValue(); } } if (success) { // Check authorization status. PHPhotoLibrary.RequestAuthorization((PHAuthorizationStatus status) => { if (status == PHAuthorizationStatus.Authorized) { // Save the movie file to the photo library and cleanup. PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => { var options = new PHAssetResourceCreationOptions(); options.ShouldMoveFile = true; var creationRequest = PHAssetCreationRequest.CreationRequestForAsset(); creationRequest.AddResource(PHAssetResourceType.Video, outputFileUrl, options); }, (cbSuccess, cbError) => { if (!cbSuccess) { Console.WriteLine($"Could not save movie to photo library: {cbError}"); } cleanup(); }); } else { cleanup(); } }); } else { cleanup(); } // Enable the Camera and Record buttons to let the user switch camera and start another recording. //DispatchQueue.MainQueue.DispatchAsync(() => //{ // // Only enable the ability to change camera if the device has more than one camera. // CameraButton.Enabled = (videoDeviceDiscoverySession.UniqueDevicePositionsCount() > 1); // RecordButton.Enabled = true; // CaptureModeControl.Enabled = true; // RecordButton.SetTitle(NSBundle.MainBundle.LocalizedString(@"Record", @"Recording button record title"), UIControlState.Normal); //}); }
void CheckPhotoLibraryAuthorizationStatus(PHAuthorizationStatus authorizationStatus) { switch (authorizationStatus) { case PHAuthorizationStatus.NotDetermined: // Vamos a pedir el permiso para acceder a la galería. //Recursivo, el parámetro es la función misma. Aquí ya entraría en los siguientes opciones //que lo haya denegado o autorizado, dependiendo de lo que haga el usuario al realizarse //la petición. //Solicitud de los permisos y su callback. PHPhotoLibrary.RequestAuthorization(CheckPhotoLibraryAuthorizationStatus); break; case PHAuthorizationStatus.Restricted: // Mostrar un mensaje diciendo que está restringido. InvokeOnMainThread(() => { ShowMessage(title: "Resource not available.", message: "The resource is not available due its restricted use.", fromViewController: NavigationController); }); break; case PHAuthorizationStatus.Denied: // Mostrar un mensaje diciendo que el usuario denegó el permiso. InvokeOnMainThread(() => { ShowMessage(title: "Resource not available.", message: "The resource is not available due it was denied by you.", fromViewController: NavigationController); }); break; case PHAuthorizationStatus.Authorized: // Vamos a abrir la galería. //Pasarse al hilo principal, ya que esta parte se ejecuta en un método asíncrono. InvokeOnMainThread(() => { //Inicializar una variable para abrir la librería de imágenes. var imagePickerController = new UIImagePickerController { SourceType = UIImagePickerControllerSourceType.PhotoLibrary, //Se asigna "this" porque aquí se está implementando el delegado. Delegate = this }; //Se presenta en pantalla la librería de imágenes. PresentViewController(imagePickerController, true, null); }); break; default: break; } }
void RequestPhotoAccess() { PHPhotoLibrary.RequestAuthorization((_) => UpdateStatus()); }
void SnapStillImage(CameraViewController sender) { SessionQueue.DispatchAsync(async() => { AVCaptureConnection connection = StillImageOutput.ConnectionFromMediaType(AVMediaType.Video); var previewLayer = (AVCaptureVideoPreviewLayer)PreviewView.Layer; // Update the orientation on the still image output video connection before capturing. connection.VideoOrientation = previewLayer.Connection.VideoOrientation; // Flash set to Auto for Still Capture. SetFlashModeForDevice(AVCaptureFlashMode.Auto, VideoDeviceInput.Device); // Capture a still image. try { var imageDataSampleBuffer = await StillImageOutput.CaptureStillImageTaskAsync(connection); // The sample buffer is not retained. Create image data before saving the still image to the photo library asynchronously. NSData imageData = AVCaptureStillImageOutput.JpegStillToNSData(imageDataSampleBuffer); PHPhotoLibrary.RequestAuthorization(status => { if (status == PHAuthorizationStatus.Authorized) { // To preserve the metadata, we create an asset from the JPEG NSData representation. // Note that creating an asset from a UIImage discards the metadata. // In iOS 9, we can use AddResource method on PHAssetCreationRequest class. // In iOS 8, we save the image to a temporary file and use +[PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:]. if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0)) { PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => { var request = PHAssetCreationRequest.CreationRequestForAsset(); request.AddResource(PHAssetResourceType.Photo, imageData, null); }, (success, err) => { if (!success) { Console.WriteLine("Error occurred while saving image to photo library: {0}", err); } }); } else { var temporaryFileUrl = new NSUrl(GetTmpFilePath("jpg"), false); PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => { NSError error = null; if (imageData.Save(temporaryFileUrl, NSDataWritingOptions.Atomic, out error)) { PHAssetChangeRequest.FromImage(temporaryFileUrl); } else { Console.WriteLine("Error occured while writing image data to a temporary file: {0}", error); } }, (success, error) => { if (!success) { Console.WriteLine("Error occurred while saving image to photo library: {0}", error); } // Delete the temporary file. NSError deleteError; NSFileManager.DefaultManager.Remove(temporaryFileUrl, out deleteError); }); } } }); } catch (NSErrorException ex) { Console.WriteLine("Could not capture still image: {0}", ex.Error); } }); }
public void FinishedRecording(AVCaptureFileOutput captureOutput, NSUrl outputFileUrl, NSObject[] connections, NSError error) { // Note that currentBackgroundRecordingID is used to end the background task associated with this recording. // This allows a new recording to be started, associated with a new UIBackgroundTaskIdentifier, once the movie file output's isRecording property // is back to NO — which happens sometime after this method returns. // Note: Since we use a unique file path for each recording, a new recording will not overwrite a recording currently being saved. var currentBackgroundRecordingID = backgroundRecordingID; backgroundRecordingID = -1; Action cleanup = () => { NSError err; NSFileManager.DefaultManager.Remove(outputFileUrl, out err); if (currentBackgroundRecordingID != -1) { UIApplication.SharedApplication.EndBackgroundTask(currentBackgroundRecordingID); } }; bool success = true; if (error != null) { Console.WriteLine("Movie file finishing error: {0}", error); success = ((NSNumber)error.UserInfo [AVErrorKeys.RecordingSuccessfullyFinished]).BoolValue; } if (!success) { cleanup(); return; } // Check authorization status. PHPhotoLibrary.RequestAuthorization(status => { if (status == PHAuthorizationStatus.Authorized) { // Save the movie file to the photo library and cleanup. PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => { // In iOS 9 and later, it's possible to move the file into the photo library without duplicating the file data. // This avoids using double the disk space during save, which can make a difference on devices with limited free disk space. if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0)) { var options = new PHAssetResourceCreationOptions { ShouldMoveFile = true }; var changeRequest = PHAssetCreationRequest.CreationRequestForAsset(); changeRequest.AddResource(PHAssetResourceType.Video, outputFileUrl, options); } else { PHAssetChangeRequest.FromVideo(outputFileUrl); } }, (success2, error2) => { if (!success2) { Console.WriteLine("Could not save movie to photo library: {0}", error2); } cleanup(); }); } else { cleanup(); } }); }
public void RequestAccessToCameraRoll() { PHPhotoLibrary.RequestAuthorization(status => { }); }
private async void SnapStillImage() { // if ((m_videoDevice != null) && (m_stillImageOutput != null)) { if (m_videoDevice.HasFlash && m_videoDevice.IsFlashModeSupported(AVCaptureFlashMode.Auto)) { NSError error; if (m_videoDevice.LockForConfiguration(out error)) { m_videoDevice.FlashMode = AVCaptureFlashMode.Auto; m_videoDevice.UnlockForConfiguration(); } } AVCaptureConnection connection = m_stillImageOutput.ConnectionFromMediaType(AVMediaType.Video); var imageDataSampleBuffer = await m_stillImageOutput.CaptureStillImageTaskAsync(connection); //获得当前帧的压缩图像 var imageData = AVCaptureStillImageOutput.JpegStillToNSData(imageDataSampleBuffer); //得到当前帧压缩图像的图像数据... //RequestAuthorization(handler), handler是用户与权限对话框交互后,执行的动作。 PHPhotoLibrary.RequestAuthorization(status => { if (status == PHAuthorizationStatus.Authorized) { // 若用户授权了 // To preserve the metadata, we create an asset from the JPEG NSData representation. // Note that creating an asset from a UIImage discards the metadata. // In iOS 9, we can use AddResource method on PHAssetCreationRequest class. // In iOS 8, we save the image to a temporary file and use +[PHAssetChangeRequest creationRequestForAssetFromImageAtFileURL:]. if (UIDevice.CurrentDevice.CheckSystemVersion(9, 0)) { //PHPhotoLibrary.SharedPhotoLibrary 返回的是一个(共享)图片库对象 //PerformChanges (changeHandler, completionHandler) changeHandler 以及 completionHandler 是一个lambda PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => { var request = PHAssetCreationRequest.CreationRequestForAsset(); request.AddResource(PHAssetResourceType.Photo, imageData, null); //保存当前照片 }, (success, err) => { if (!success) { Console.WriteLine("Error occurred while saving image to photo library: {0}", err); } }); } else { //用户没有授权 string outputFileName = NSProcessInfo.ProcessInfo.GloballyUniqueString; string tmpDir = Path.GetTempPath(); string outputFilePath = Path.Combine(tmpDir, outputFileName); string outputFilePath2 = Path.ChangeExtension(outputFilePath, "jpg"); NSUrl temporaryFileUrl = new NSUrl(outputFilePath2, false); PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => { NSError error = null; if (imageData.Save(temporaryFileUrl, NSDataWritingOptions.Atomic, out error)) { PHAssetChangeRequest.FromImage(temporaryFileUrl); } else { Console.WriteLine("Error occured while writing image data to a temporary file: {0}", error); } }, (success, error) => { if (!success) { Console.WriteLine("Error occurred while saving image to photo library: {0}", error); } // Delete the temporary file. NSError deleteError; NSFileManager.DefaultManager.Remove(temporaryFileUrl, out deleteError); }); } } }); } }
public void FinishedRecording(AVCaptureFileOutput captureOutput, NSUrl outputFileUrl, NSObject[] connections, NSError error) { // Note that currentBackgroundRecordingID is used to end the background task associated with this recording. // This allows a new recording to be started, associated with a new UIBackgroundTaskIdentifier, once the movie file output's isRecording property // is back to false — which happens sometime after this method returns. // Note: Since we use a unique file path for each recording, a new recording will not overwrite a recording currently being saved. Action cleanup = () => { var path = outputFileUrl.Path; if (NSFileManager.DefaultManager.FileExists(path)) { NSError err; if (!NSFileManager.DefaultManager.Remove(path, out err)) { Console.WriteLine($"Could not remove file at url: {outputFileUrl}"); } } var currentBackgroundRecordingID = backgroundRecordingID; if (currentBackgroundRecordingID != -1) { backgroundRecordingID = -1; UIApplication.SharedApplication.EndBackgroundTask(currentBackgroundRecordingID); } }; bool success = true; if (error != null) { Console.WriteLine($"Movie file finishing error: {error.LocalizedDescription}"); success = ((NSNumber)error.UserInfo[AVErrorKeys.RecordingSuccessfullyFinished]).BoolValue; } if (success) { // Check authorization status. PHPhotoLibrary.RequestAuthorization(status => { if (status == PHAuthorizationStatus.Authorized) { // Save the movie file to the photo library and cleanup. PHPhotoLibrary.SharedPhotoLibrary.PerformChanges(() => { var options = new PHAssetResourceCreationOptions { ShouldMoveFile = true }; var creationRequest = PHAssetCreationRequest.CreationRequestForAsset(); creationRequest.AddResource(PHAssetResourceType.Video, outputFileUrl, options); }, (success2, error2) => { if (!success2) { Console.WriteLine($"Could not save movie to photo library: {error2}"); } cleanup(); }); } else { cleanup(); } }); } else { cleanup(); } // Enable the Camera and Record buttons to let the user switch camera and start another recording. DispatchQueue.MainQueue.DispatchAsync(() => { // Only enable the ability to change camera if the device has more than one camera. CameraButton.Enabled = UniqueDevicePositionsCount(videoDeviceDiscoverySession) > 1; RecordButton.Enabled = true; CaptureModeControl.Enabled = true; RecordButton.SetTitle("Record", UIControlState.Normal); }); }