Ejemplo n.º 1
0
    public static void RequestCameraPermission(NSString mediaTypeToken, bool assert_granted = false)
    {
#if __MACCATALYST__
        // Microphone requires a hardened runtime entitlement for Mac Catalyst: com.apple.security.device.microphonee,
        // so just ignore these tests for now.
        NUnit.Framework.Assert.Ignore("Requires a hardened runtime entitlement: com.apple.security.device.microphone");
#endif // __MACCATALYST__

        if (AVCaptureDevice.GetAuthorizationStatus(mediaTypeToken) == AVAuthorizationStatus.NotDetermined)
        {
            if (IgnoreTestThatRequiresSystemPermissions())
            {
                NUnit.Framework.Assert.Ignore("This test would show a dialog to ask for permission to access the camera.");
            }

            AVCaptureDevice.RequestAccessForMediaType(mediaTypeToken, (accessGranted) =>
            {
                Console.WriteLine("Camera permission {0}", accessGranted ? "granted" : "denied");
            });
        }

        switch (AVCaptureDevice.GetAuthorizationStatus(AVMediaTypes.Video.GetConstant()))
        {
        case AVAuthorizationStatus.Restricted:
        case AVAuthorizationStatus.Denied:
            if (assert_granted)
            {
                NUnit.Framework.Assert.Fail("This test requires permission to access the camera.");
            }
            break;
        }
    }
        /// <summary>
        /// Opens a camera capture view controller.
        /// </summary>
        /// <param name="parent">The parent view controller that invoked the method.</param>
        /// <param name="callback">Action to call after photo is captured.</param>
        /// <param name="onCancel">Action to call if canceling from camera.</param>
        /// <param name="cameraToUse">Can set to default the front or rear camera.</param>
        public static void TakePicture <TViewModel>(BaseViewController <TViewModel> parent, Action <NSDictionary> callback, Action onCancel, UIImagePickerControllerCameraDevice cameraToUse = UIImagePickerControllerCameraDevice.Front)
            where TViewModel : BaseViewModel
        {
            var status = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);

            if (status == AVAuthorizationStatus.NotDetermined)
            {
                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (accessGranted) =>
                {
                    if (accessGranted)
                    {
                        // Open the camera
                        parent.InvokeOnMainThread(delegate
                        {
                            InitializeCamera(parent, callback, onCancel, cameraToUse);
                        });
                    }
                    // If they have said no do nothing.
                });
            }
            else if (status == AVAuthorizationStatus.Authorized)
            {
                // Open the camera
                InitializeCamera(parent, callback, onCancel, cameraToUse);
            }
            else
            {
                // They said no in the past, so show them an alert to direct them to the app's settings.
                OpenSettingsAlert(parent, "Camera Access Required", "Authorization to access the camera is required to use this feature of the app.");
            }
        }
Ejemplo n.º 3
0
 void ShowActualAVPermissionAlertWithType(ClusterAVAuthorizationType mediaType)
 {
     AVCaptureDevice.RequestAccessForMediaType(AVEquivalentMediaType(mediaType), granted => BeginInvokeOnMainThread(delegate
     {
         FireAVPermissionCompletionHandlerWithType(mediaType);
     }));
 }
Ejemplo n.º 4
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();


            // Disable UI. The UI is enabled if and only if the session starts running.

            // Add the open barcode gesture recognizer to the region of interest view.

            // Set up the video preview view.
            this.PreviewView.Session = session;

            // Check video authorization status. Video access is required and audio
            // access is optional. If audio access is denied, audio is not recorded
            // during movie recording.
            switch (AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video))
            {
            case AVAuthorizationStatus.Authorized:
                // The user has previously granted access to the camera.
                break;

            case AVAuthorizationStatus.NotDetermined:
                // The user has not yet been presented with the option to grant
                // video access. We suspend the session queue to delay session
                // setup until the access request has completed.
                this.sessionQueue.Suspend();
                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (granted) =>
                {
                    if (!granted)
                    {
                        this.setupResult = SessionSetupResult.NotAuthorized;
                    }

                    this.sessionQueue.Resume();
                });
                break;

            default:
                // The user has previously denied access.
                this.setupResult = SessionSetupResult.NotAuthorized;
                break;
            }

            // Setup the capture session.
            // In general it is not safe to mutate an AVCaptureSession or any of its
            // inputs, outputs, or connections from multiple threads at the same time.
            //
            // Why not do all of this on the main queue?
            // Because AVCaptureSession.StartRunning() is a blocking call which can
            // take a long time. We dispatch session setup to the sessionQueue so
            // that the main queue isn't blocked, which keeps the UI responsive.
            this.sessionQueue.DispatchAsync(this.ConfigureSession);

            UISlider focusSlider = new UISlider(new CGRect(60, this.View.Frame.Location.Y - 60, 200, 20));

            // focusSlider.AddTarget(focusSlider, new ObjCRuntime.Selector(AdjustFocusAction), UIControlEvent.ValueChanged);
            focusSlider.MaxValue = 1;
            focusSlider.MinValue = 0;
            this.View.AddSubview(focusSlider);
        }
 private void CheckPermissionAndRunAgoraEngine()
 {
     SetError(string.Empty);
     AVCaptureDevice.RequestAccessForMediaType(AVAuthorizationMediaType.Audio, (accessGranted) =>
     {
         BeginInvokeOnMainThread(() =>
         {
             if (accessGranted)
             {
                 _agoraKit = AgoraRtcEngineKit.SharedEngineWithAppId(AgoraTestConstants.AgoraAPI, (error) =>
                 {
                     SetError($"Could not init agora. {error}");
                     SetControlsVisible(false);
                 });
                 JoinChannel();
                 SetControlsVisible(true);
             }
             else
             {
                 SetError("Permission denied. Please allow access to microphone");
                 SetControlsVisible(false);
             }
         });
     });
 }
Ejemplo n.º 6
0
        public void Prepare(AVCaptureVideoOrientation captureVideoOrientation)
        {
            var status = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);

            if (status == AVAuthorizationStatus.NotDetermined)
            {
                _sessionQueue.Suspend();
                AVCaptureDevice.RequestAccessForMediaType(AVAuthorizationMediaType.Video, granted =>
                {
                    if (granted)
                    {
                        DispatchQueue.MainQueue.DispatchAsync(() =>
                        {
                            _captureSessionDelegate.CaptureGrantedSession(AVAuthorizationStatus.Authorized);
                        });
                    }
                    else
                    {
                        _setupResult = SessionSetupResult.NotAuthorized;
                    }

                    _sessionQueue.Resume();
                });
            }
            else if (status != AVAuthorizationStatus.Authorized)
            {
                _setupResult = SessionSetupResult.NotAuthorized;
            }

            _sessionQueue.DispatchAsync(() =>
            {
                ConfigureSession();
                UpdateVideoOrientation(captureVideoOrientation);
            });
        }
Ejemplo n.º 7
0
        private void Setup()
        {
            AVAuthorizationStatus authorizationStatus = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);

            switch (authorizationStatus)
            {
            case AVAuthorizationStatus.NotDetermined: {
                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, new AVRequestAccessStatus(delegate(bool accessGranted) {
                        if (accessGranted)
                        {
                            SetupCapture();
                        }
                        else
                        {
                            Console.WriteLine("Access denied");
                        }
                    }));
                break;
            }

            case AVAuthorizationStatus.Authorized: {
                SetupCapture();
                break;
            }

            case AVAuthorizationStatus.Restricted: {
                Console.WriteLine("Access denied");
                break;
            }

            default: {
                break;
            }
            }
        }
Ejemplo n.º 8
0
        public void MakeSnapshot(string path, int size, Action <bool> callback)
        {
            AVAuthorizationStatus status = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);

            switch (status)
            {
            case AVAuthorizationStatus.NotDetermined:
                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, granded =>
                {
                    if (granded)
                    {
                        Context.MainController.InvokeOnMainThread(() => Write(path, size, callback));
                    }
                });
                break;

            case AVAuthorizationStatus.Restricted:
            case AVAuthorizationStatus.Denied:
                using (var alert = new UIAlertView(D.WARNING, D.CAMERA_NOT_ALLOWED, null, D.OK))
                    alert.Show();
                break;

            case AVAuthorizationStatus.Authorized:
                Write(path, size, callback);
                break;
            }
        }
Ejemplo n.º 9
0
 public void askUserForCameraPermissions(Action <bool> completion)
 {
     AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, allowed =>
     {
         completion(allowed);
     });
 }
Ejemplo n.º 10
0
        private void CheckVideoPermissionAndStart()
        {
            AVFoundation.AVAuthorizationStatus authorizationStatus = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);
            switch (authorizationStatus)
            {
            case AVAuthorizationStatus.NotDetermined:
                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, delegate(bool granted)
                {
                    if (granted)
                    {
                        SetupCaptureSession();
                    }
                    else
                    {
                        RenderImageMessage("Please grant Video Capture permission");
                    }
                });
                break;

            case AVAuthorizationStatus.Authorized:
                SetupCaptureSession();
                break;

            case AVAuthorizationStatus.Denied:
            case AVAuthorizationStatus.Restricted:
                RenderImageMessage("Please grant Video Capture permission");
                break;

            default:

                break;
                //do nothing
            }
        }
Ejemplo n.º 11
0
        private UIAlertAction AbrirCamara(UIImagePickerController ImagePicker)
        {
            const String HeaderMessage = "Se necesita acceso a la camara";
            const String BodyMessage   = "Habilita el acceso de Worklabs a la camara en la configuración de tu iPhone";

            UIAlertAction openCamera = UIAlertAction.Create("Tomar fotografia", UIAlertActionStyle.Default, (action) =>
            {
                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (bool isAccessGranted) =>
                {
                    InvokeOnMainThread(() =>
                    {
                        try
                        {
                            if (isAccessGranted)
                            {
                                ImagePicker.SourceType    = UIImagePickerControllerSourceType.Camera;
                                ImagePicker.CameraDevice  = UIImagePickerControllerCameraDevice.Rear;
                                ImagePicker.AllowsEditing = true;
                                this.PresentViewController(ImagePicker, true, null);
                            }
                            else
                            {
                                this.PresentViewController(this.PermisosDispositivo(HeaderMessage, BodyMessage), true, null);
                            }
                        }
                        catch (Exception e)
                        {
                            SlackLogs.SendMessage(e.Message, "", "AbrirCamara");
                        }
                    });
                });
            });

            return(openCamera);
        }
Ejemplo n.º 12
0
    public static void RequestCameraPermission(NSString mediaTypeToken, bool assert_granted = false)
    {
        if (AVCaptureDevice.GetAuthorizationStatus(mediaTypeToken) == AVAuthorizationStatus.NotDetermined)
        {
            if (IgnoreTestThatRequiresSystemPermissions())
            {
                NUnit.Framework.Assert.Ignore("This test would show a dialog to ask for permission to access the camera.");
            }

            AVCaptureDevice.RequestAccessForMediaType(mediaTypeToken, (accessGranted) =>
            {
                Console.WriteLine("Camera permission {0}", accessGranted ? "granted" : "denied");
            });
        }

        switch (AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video))
        {
        case AVAuthorizationStatus.Restricted:
        case AVAuthorizationStatus.Denied:
            if (assert_granted)
            {
                NUnit.Framework.Assert.Fail("This test requires permission to access the camera.");
            }
            break;
        }
    }
Ejemplo n.º 13
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Disable UI. The UI is enabled if and only if the session starts running.
            this.MetadataObjectTypesButton.Enabled = false;
            this.SessionPresetsButton.Enabled      = false;
            this.CameraButton.Enabled = false;
            this.ZoomSlider.Enabled   = false;

            // Add the open barcode gesture recognizer to the region of interest view.
            this.PreviewView.AddGestureRecognizer(this.OpenBarcodeURLGestureRecognizer);

            // Set up the video preview view.
            this.PreviewView.Session = session;

            // Check video authorization status. Video access is required and audio
            // access is optional. If audio access is denied, audio is not recorded
            // during movie recording.
            switch (AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video))
            {
            case AVAuthorizationStatus.Authorized:
                // The user has previously granted access to the camera.
                break;

            case AVAuthorizationStatus.NotDetermined:
                // The user has not yet been presented with the option to grant
                // video access. We suspend the session queue to delay session
                // setup until the access request has completed.
                this.sessionQueue.Suspend();
                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (granted) =>
                {
                    if (!granted)
                    {
                        this.setupResult = SessionSetupResult.NotAuthorized;
                    }

                    this.sessionQueue.Resume();
                });
                break;

            default:
                // The user has previously denied access.
                this.setupResult = SessionSetupResult.NotAuthorized;
                break;
            }

            // Setup the capture session.
            // In general it is not safe to mutate an AVCaptureSession or any of its
            // inputs, outputs, or connections from multiple threads at the same time.
            //
            // Why not do all of this on the main queue?
            // Because AVCaptureSession.StartRunning() is a blocking call which can
            // take a long time. We dispatch session setup to the sessionQueue so
            // that the main queue isn't blocked, which keeps the UI responsive.
            this.sessionQueue.DispatchAsync(this.ConfigureSession);
        }
Ejemplo n.º 14
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            //systemSoundBeep = new SystemSound(NSUrl.FromFilename("Sounds/beep07.mp3"));
            //systemSoundCaution = new SystemSound(NSUrl.FromFilename("Sounds/beep06.mp3"));

            //audioPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename("Sounds/beep07.mp3"));
            //audioCautionPlayer = AVAudioPlayer.FromUrl(NSUrl.FromFilename("Sounds/beep06.mp3"));

            // Perform any additional setup after loading the view, typically from a nib.
            this.PreviewView.AddGestureRecognizer(this.OpenBarcodeURLGestureRecognizer);

            // Set up the video preview view.
            this.PreviewView.Session = session;

            // Check video authorization status. Video access is required and audio
            // access is optional. If audio access is denied, audio is not recorded
            // during movie recording.
            switch (AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video))
            {
            case AVAuthorizationStatus.Authorized:
                // The user has previously granted access to the camera.
                break;

            case AVAuthorizationStatus.NotDetermined:
                // The user has not yet been presented with the option to grant
                // video access. We suspend the session queue to delay session
                // setup until the access request has completed.
                this.sessionQueue.Suspend();
                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (granted) =>
                {
                    if (!granted)
                    {
                        this.setupResult = SessionSetupResult.NotAuthorized;
                    }

                    this.sessionQueue.Resume();
                });
                break;

            default:
                // The user has previously denied access.
                this.setupResult = SessionSetupResult.NotAuthorized;
                break;
            }

            // Setup the capture session.
            // In general it is not safe to mutate an AVCaptureSession or any of its
            // inputs, outputs, or connections from multiple threads at the same time.
            //
            // Why not do all of this on the main queue?
            // Because AVCaptureSession.StartRunning() is a blocking call which can
            // take a long time. We dispatch session setup to the sessionQueue so
            // that the main queue isn't blocked, which keeps the UI responsive.
            this.sessionQueue.DispatchAsync(this.ConfigureSession);
        }
Ejemplo n.º 15
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            View.BackgroundColor = UIColor.FromRGBA(0.0f, 0.0f, 0.0f, 1f);

            // ここにInitUI()の呼び出しを書く


            // Disable UI. The UI is enabled if and only if the session starts running.
            CameraButton.Enabled        = false;
            RecordButton.Enabled        = false;
            PhotoButton.Enabled         = false;
            LivePhotoModeButton.Enabled = false;
            CaptureModeControl.Enabled  = false;

            // Setup the preview view.
            PreviewView.Session = session;

            // Check video authorization status. Video access is required and audio access is optional.
            // If audio access is denied, audio is not recorded during movie recording.
            switch (AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video))
            {
            // The user has previously granted access to the camera.
            case AVAuthorizationStatus.Authorized:
                break;

            // The user has not yet been presented with the option to grant video access.
            // We suspend the session queue to delay session setup until the access request has completed to avoid
            // asking the user for audio access if video access is denied.
            // Note that audio access will be implicitly requested when we create an AVCaptureDeviceInput for audio during session setup.
            case AVAuthorizationStatus.NotDetermined:
                sessionQueue.Suspend();
                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, granted => {
                    if (!granted)
                    {
                        setupResult = AVCamSetupResult.CameraNotAuthorized;
                    }
                    sessionQueue.Resume();
                });
                break;

            // The user has previously denied access.
            default:
                setupResult = AVCamSetupResult.CameraNotAuthorized;
                break;
            }

            // Setup the capture session.
            // In general it is not safe to mutate an AVCaptureSession or any of its inputs, outputs, or connections from multiple threads at the same time.
            // Why not do all of this on the main queue?
            // Because AVCaptureSession.StartRunning is a blocking call which can take a long time. We dispatch session setup to the sessionQueue
            // so that the main queue isn't blocked, which keeps the UI responsive.
            sessionQueue.DispatchAsync(ConfigureSession);
        }
Ejemplo n.º 16
0
        void CheckCameraAuthorizationStatus(AVAuthorizationStatus aVAuthorizationStatus)
        {
            switch (aVAuthorizationStatus)
            {
            case AVAuthorizationStatus.NotDetermined:

                //Solicitud del permiso.
                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (bool accessGranted) => CheckCameraAuthorizationStatus(AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video)));

                break;

            case AVAuthorizationStatus.Restricted:

                InvokeOnMainThread(() => {
                    ShowMessage(title: "Resource not available.", message: "The resource is not available due its restricted use.", fromViewController: NavigationController);
                });

                break;

            case AVAuthorizationStatus.Denied:

                InvokeOnMainThread(() => {
                    ShowMessage(title: "Resource not available.", message: "The resource is not available due it was denied by you.", fromViewController: NavigationController);
                });

                break;

            case AVAuthorizationStatus.Authorized:

                //Abrir la cámara.

                InvokeOnMainThread(() => {
                    var imagePickerController = new UIImagePickerController
                    {
                        SourceType = UIImagePickerControllerSourceType.Camera,
                        Delegate   = this
                    };

                    PresentViewController(imagePickerController, true, null);
                });

                break;


            default:

                break;
            }
        }
Ejemplo n.º 17
0
 public void askUserForCameraPermissions(Action <bool> completion)
 {
     AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, allowed =>
     {
         if (this.OutputMode == CameraOutputMode.VideoWithMic)
         {
             AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Audio, audioAllowed =>
             {
                 completion(audioAllowed);
             });
         }
         else
         {
             completion(allowed);
         }
     });
 }
Ejemplo n.º 18
0
        //-------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------------
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            // Create the AVCaptureSession.
            session = new AVCaptureSession();

            // Set up the preview view.
            PreviewView.Session = session;

            setupResult = AVCamSetupResult.Success;

            switch (AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video))
            {
            case AVAuthorizationStatus.Authorized:
                // The user has previously granted access to the camera.
                break;

            case AVAuthorizationStatus.NotDetermined:

                /*
                 *  The user has not yet been presented with the option to grant
                 *  video access. We suspend the session queue to delay session
                 *  setup until the access request has completed.
                 *
                 *  Note that audio access will be implicitly requested when we
                 *  create an AVCaptureDeviceInput for audio during session setup.
                 */
                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (bool granted) => {
                    if (!granted)
                    {
                        setupResult = AVCamSetupResult.CameraNotAuthorized;
                    }
                });
                break;

            default:
            {
                // The user has previously denied access.
                setupResult = AVCamSetupResult.CameraNotAuthorized;
                break;
            }
            }

            ConfigureSession();
        }
Ejemplo n.º 19
0
        private void GetFromCamera()
        {
            AVAuthorizationStatus authStatus = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);

            if (authStatus == AVAuthorizationStatus.Authorized)
            {
                DoPhoto();
                return;
            }

            AVCaptureDevice.RequestAccessForMediaType(AVAuthorizationMediaType.Video, (bool access) =>
            {
                if (access == true)
                {
                    DoPhoto();
                }
                ;
            });
        }
Ejemplo n.º 20
0
        private static void RequestCamera()
        {
            var status = AVCaptureDevice.GetAuthorizationStatus(AVAuthorizationMediaType.Video);

            if (status != AVAuthorizationStatus.NotDetermined)
            {
                RaiseAuthorizationRequested(AuthorizationType.Camera, status.ToShared());
                return;
            }

            if (_requests.TryGetValue(AuthorizationType.Camera, out var value))
            {
                var result = _requests.TryUpdate(AuthorizationType.Camera, value + 1, value);
            }
            else
            {
                _requests.TryAdd(AuthorizationType.Camera, 1);
                AVCaptureDevice.RequestAccessForMediaType(AVAuthorizationMediaType.Video, OnCameraRequested);
            }
        }
        void CheckCameraAuthorizationStatus(AVAuthorizationStatus authorizationStatus)
        {
            switch (authorizationStatus)
            {
            case AVAuthorizationStatus.NotDetermined:
                //TODO: Vamos a pedir el permiso para acceder
                AVCaptureDevice.RequestAccessForMediaType(AVAuthorizationMediaType.Video, (accessGranted) => {
                    if (!accessGranted)
                    {
                        CheckCameraAuthorizationStatus(authorizationStatus);
                    }
                });
                break;

            case AVAuthorizationStatus.Restricted:
                //TODO: Mostrar un mensaje diciendo que esta restringido
                InvokeOnMainThread(() => ShowMessage("Error", "El permiso esta restringido.", NavigationController));
                break;

            case AVAuthorizationStatus.Denied:
                //TODO: El usuario denego el permiso.
                InvokeOnMainThread(() => ShowMessage("Error", "El permiso fue denegado.", NavigationController));
                break;

            case AVAuthorizationStatus.Authorized:
                //TODO: Abrir la galeria
                InvokeOnMainThread(() =>
                {
                    var imagePickerController = new UIImagePickerController
                    {
                        SourceType = UIImagePickerControllerSourceType.Camera,
                        Delegate   = this
                    };
                    PresentViewController(imagePickerController, true, null);
                });
                break;

            default:
                break;
            }
        }
        void CheckCameraAuthorizationStatus(AVAuthorizationStatus auth)
        {
            switch (auth)
            {
            case AVAuthorizationStatus.Authorized:
                InvokeOnMainThread(() =>
                {
                    var imagePicker = new UIImagePickerController
                    {
                        SourceType = UIImagePickerControllerSourceType.Camera,
                        Delegate   = this
                    };
                    PresentViewController(imagePicker, true, null);
                });
                break;

            case AVAuthorizationStatus.Denied:
                InvokeOnMainThread(() =>
                {
                    ShowMessage("Alert!", "No", NavigationController);
                });
                break;

            case AVAuthorizationStatus.NotDetermined:

                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (bool access) => CheckCameraAuthorizationStatus(auth));
                break;

            case AVAuthorizationStatus.Restricted:
                InvokeOnMainThread(() =>
                {
                    ShowMessage("Alert!", "No", NavigationController);
                });
                break;

            default:
                break;
            }
        }
Ejemplo n.º 23
0
            public override void ViewDidLoad()
            {
                base.ViewDidLoad();
                View.BackgroundColor = UIColor.Black;

                NSError error = null;

                _captureSession = new AVCaptureSession();
                CameraMetaDataDelegate del = null;

                var             authStatus    = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);
                AVCaptureDevice captureDevice = null;

                // check authorization status
                if (authStatus == AVAuthorizationStatus.Authorized)
                {
                    captureDevice = AVCaptureDevice.GetDefaultDevice(AVMediaType.Video); // update for iOS 13
                }
                else if (authStatus == AVAuthorizationStatus.NotDetermined)
                {
                    AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (granted) =>
                    {
                        if (!granted)
                        {
                            iApp.Log.Error("ViewDidLoadBase ScanLayer RequestAccessForMediaType not granted!");
                        }
                        else
                        {
                            iApp.Log.Error("ViewDidLoadBase ScanLayer RequestAccessForMediaType granted!");
                        }
                    });
                }
                else
                {
                    iApp.Log.Error("Not Authorized! Status: " + authStatus.ToString());
                }
                if (captureDevice != null)
                {
                    var videoInput = AVCaptureDeviceInput.FromDevice(captureDevice, out error);
                    if (videoInput != null)
                    {
                        _captureSession.AddInput(videoInput);
                    }
                    else
                    {
                        iApp.Log.Error("Video capture error: " + error.LocalizedDescription);
                    }

                    var metaDataOutput = new AVCaptureMetadataOutput();
                    _captureSession.AddOutput(metaDataOutput);

                    del = new CameraMetaDataDelegate(this, _layer);
                    metaDataOutput.SetDelegate(del, CoreFoundation.DispatchQueue.MainQueue);

                    //metaDataOutput.MetadataObjectTypes = metaDataOutput.AvailableMetadataObjectTypes;

                    metaDataOutput.MetadataObjectTypes = AVMetadataObjectType.QRCode | AVMetadataObjectType.Code128Code | AVMetadataObjectType.UPCECode | AVMetadataObjectType.EAN13Code;


                    _videoPreviewLayer = new AVCaptureVideoPreviewLayer(_captureSession)
                    {
                        Frame       = View.Bounds,
                        Orientation = (AVCaptureVideoOrientation)InterfaceOrientation,
                    };
                    View.Layer.AddSublayer(_videoPreviewLayer);
                    var image = TouchStyle.ImageFromResource("barcode-overlay-sm.png");
                    _imageOverlay = new UIImageView(image)
                    {
                        Frame            = View.Frame,
                        ContentMode      = UIViewContentMode.Center,
                        AutoresizingMask = UIViewAutoresizing.FlexibleMargins,
                    };
                    View.Add(_imageOverlay);

                    // preload this, and display when scan event occurs
                    var imageScanBlocked = TouchStyle.ImageFromResource("barcode-scanblocked-sm.png");
                    _imageOverlayScanBlocked = new UIImageView(imageScanBlocked)
                    {
                        Frame            = View.Frame,
                        ContentMode      = UIViewContentMode.Center,
                        AutoresizingMask = UIViewAutoresizing.FlexibleMargins,
                        Hidden           = true,
                    };
                    View.Add(_imageOverlayScanBlocked);
                }
                else
                {
                    //TODO: Add "Scanner currently not active overlay Image"
                    iApp.Log.Error("null capture device!");
                }

                nfloat startVerticalLoc = UIScreen.MainScreen.Bounds.Height - LastValueScanOverlay.ViewHeight;

                _lastScanOverlay = new LastValueScanOverlay(startVerticalLoc, _layerFont);
                View.Add(_lastScanOverlay);

                NavigationItem.LeftBarButtonItem = new UIBarButtonItem("Done", UIBarButtonItemStyle.Done, delegate {
                    string scannedBarcodes = string.Empty;
                    if (del != null && del.Buffer != null && del.Buffer.CurrentBuffer != null)
                    {
                        foreach (var s in del.Buffer.CurrentBuffer)
                        {
                            scannedBarcodes += s + "\r\n";
                        }
                    }
                    if (_callback.Parameters == null)
                    {
                        _callback.Parameters = new Dictionary <string, string>();
                    }
                    _callback.Parameters[_barcodeValueKey] = scannedBarcodes;
                    iApp.Navigate(_callback);
                    ModalManager.EnqueueModalTransition(TouchFactory.Instance.TopViewController, null, true);
                });
            }
Ejemplo n.º 24
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();
            this.View.BackgroundColor = UIColor.White;
            int v = 0;

            if (UIDevice.CurrentDevice.CheckSystemVersion(7, 0))
            {
                v = 20;
            }
            nfloat  height = this.View.Frame.Height / 2 - v;
            CGRect  frame  = new CGRect(0, v, this.View.Frame.Width, height);
            UIImage image  = TouchStyle.ImageFromResource("barcode-overlay-sm.png");

            this._imageOverlay = new UIImageView(image)
            {
                Frame            = frame,
                ContentMode      = UIViewContentMode.Center,
                AutoresizingMask = (UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleBottomMargin)
            };
            this.View.Add(this._imageOverlay);
            UIImage image2 = TouchStyle.ImageFromResource("barcode-scanblocked-sm.png");

            this._imageOverlayScanBlocked = new UIImageView(image2)
            {
                Frame            = frame,
                ContentMode      = UIViewContentMode.Center,
                AutoresizingMask = (UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleBottomMargin),
                Hidden           = true
            };
            this.View.Add(this._imageOverlayScanBlocked);
            this._cameraView = new UIView
            {
                AutoresizingMask = (UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight | UIViewAutoresizing.FlexibleBottomMargin)
            };
            this._cameraView.Frame = frame;

            AVAuthorizationStatus authorizationStatus = AVCaptureDevice.GetAuthorizationStatus(AVMediaType.Video);

            if (authorizationStatus == AVAuthorizationStatus.Authorized)
            {
                AVCaptureDevice      device = AVCaptureDevice.GetDefaultDevice(AVMediaType.Video); // update for iOS 13
                NSError              nSError;
                AVCaptureDeviceInput aVCaptureDeviceInput = AVCaptureDeviceInput.FromDevice(device, out nSError);
                if (aVCaptureDeviceInput != null)
                {
                    this._captureSession = new AVCaptureSession();
                    this._captureSession.AddInput(aVCaptureDeviceInput);
                    AVCaptureMetadataOutput aVCaptureMetadataOutput = new AVCaptureMetadataOutput();
                    this._captureSession.AddOutput(aVCaptureMetadataOutput);
                    this._cameraMetaDataDelegate = new CameraScannerSplitView.CameraMetaDataDelegate(this);
                    aVCaptureMetadataOutput.SetDelegate(this._cameraMetaDataDelegate, DispatchQueue.MainQueue);
                    //aVCaptureMetadataOutput.MetadataObjectTypes = aVCaptureMetadataOutput.AvailableMetadataObjectTypes;
                    aVCaptureMetadataOutput.MetadataObjectTypes = AVMetadataObjectType.QRCode | AVMetadataObjectType.Code128Code | AVMetadataObjectType.UPCECode | AVMetadataObjectType.EAN13Code;
                }
            }
            else if (authorizationStatus == AVAuthorizationStatus.NotDetermined)
            {
                AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, (granted) =>
                {
                    if (!granted)
                    {
                        Device.Log.Error("ViewDidLoadBase ScanLayer RequestAccessForMediaType not granted!");
                    }
                    else
                    {
                        Device.Log.Error("ViewDidLoadBase ScanLayer RequestAccessForMediaType granted!");
                    }
                });
            }
            else
            {
                Device.Log.Error("Not Authorized! Status: " + authorizationStatus.ToString());
            }


            if (authorizationStatus >= AVAuthorizationStatus.NotDetermined && authorizationStatus <= AVAuthorizationStatus.Authorized)
            {
                switch ((int)authorizationStatus)
                {
                case 0:
                    AVCaptureDevice.RequestAccessForMediaType(AVMediaType.Video, delegate(bool result)
                    {
                        Device.Thread.ExecuteOnMainThread(delegate
                        {
                            if (result)
                            {
                                this.SetupVideoPreviewLayer();
                            }
                            else
                            {
                                this.AddNoCameraAccessLabels();
                            }
                        });
                    });
                    break;

                case 1:
                    Device.Log.Warn("Camera Access is restricted", new object[0]);
                    this.AddNoCameraAccessLabels();
                    break;

                case 2:
                    this.AddNoCameraAccessLabels();
                    break;

                case 3:
                    this.SetupVideoPreviewLayer();
                    break;
                }
            }
            this.View.InsertSubviewBelow(this._cameraView, this._imageOverlay);
            CGRect frame2 = new CGRect(0, frame.Bottom, this.View.Frame.Width, this.View.Frame.Height - frame.Height);

            this._resultsView = new UITableView(frame2, UITableViewStyle.Plain)
            {
                AutoresizingMask = (UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin | UIViewAutoresizing.FlexibleHeight)
            };
            this._resultsView.Source = new CameraScannerSplitView.CameraListSource(this);
            this.View.Add(this._resultsView);
            this.NavigationItem.LeftBarButtonItem = new UIBarButtonItem("Done", UIBarButtonItemStyle.Done, delegate
            {
                string text = string.Empty;
                if (this._resultsView.Source != null)
                {
                    try
                    {
                        string text2       = string.Empty;
                        List <string> list = (this._resultsView.Source as CameraScannerSplitView.CameraListSource).ScannedBarcodes();
                        foreach (string current in list)
                        {
                            if (!string.IsNullOrEmpty(current))
                            {
                                text2 = text2 + current + "\r\n";
                            }
                        }
                        text = text2;
                    }
                    catch (Exception arg)
                    {
                        Device.Log.Error("This error occurred while parsing barcodes scanned: \r\n" + arg, new object[0]);
                    }
                }
                if (this._callback.Parameters == null)
                {
                    this._callback.Parameters = new Dictionary <string, string>();
                }
                this._callback.Parameters[this._barcodeValueKey] = text;
                iApp.Navigate(this._callback);
                ModalManager.EnqueueModalTransition(TouchFactory.Instance.TopViewController, null, true);
            });
        }
Ejemplo n.º 25
0
 void AskForCameraPermission()
 {
     AVCaptureDevice.RequestAccessForMediaType(AVAuthorizationMediaType.Video, (accessGranted) => InvokeOnMainThread(CheckCameraPermission));
 }