Search code examples
c#cameraxamarin.formsxlabs

Access to Camera in Xamarin.Forms


I need to access the camera in with Xamarin Forms PCL. I couldn't find any sample that works.

I tried by installing XLab and using its sample code but it has exceptions. For instance, with the XLabs sample I am using the following:

/// <summary>
/// Takes the picture.
/// </summary>
/// <returns>Take Picture Task.</returns>
internal async Task<MediaFile> TakePicture()
{
    Setup();

    ImageSource = null;

    return await _mediaPicker.TakePhotoAsync(new CameraMediaStorageOptions { DefaultCamera = CameraDevice.Front, MaxPixelDimension = 400 }).ContinueWith(t =>
    {
        if (t.IsFaulted)
        {
            Status = t.Exception.InnerException.ToString();
        }
        else if (t.IsCanceled)
        {
            Status = "Canceled";
        }
        else
        {
            var mediaFile = t.Result;

            ImageSource = ImageSource.FromStream(() => mediaFile.Source);

            return mediaFile;
        }

        return null;
    }, _scheduler);
}

/// <summary>
/// Setups this instance.
/// </summary>
private void Setup()
{
    if (_mediaPicker != null)
    {
        return;
    }

    var device = Resolver.Resolve<IDevice>();

    ////RM: hack for working on windows phone? 
    _mediaPicker = DependencyService.Get<IMediaPicker>() ?? device.MediaPicker;
}

I get the following exception on Resolver.Resolve<IDevice>(): IResolver has not been set. Please set it by calling Resolver.SetResolver(resolver)

How can I use this or other alternative to take picture with Xamarin.Forms? thanks for any tip in advance!


Solution

  • Add in your Droid Project, class MainActivity this code

    protected override void OnCreate (Bundle bundle)
    {
        base.OnCreate (bundle);
        #region Resolver Init
        SimpleContainer container = new SimpleContainer();
        container.Register<IDevice>(t => AndroidDevice.CurrentDevice);
        container.Register<IDisplay>(t => t.Resolve<IDevice>().Display);
        container.Register<INetwork>(t => t.Resolve<IDevice>().Network);
    
        Resolver.SetResolver(container.GetResolver());
        #endregion
        ....
    }
    

    and in IOS class AppDelegate this one:

    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        #region Resolver Init
        SimpleContainer container = new SimpleContainer();
        container.Register<IDevice>(t => AppleDevice.CurrentDevice);
        container.Register<IDisplay>(t => t.Resolve<IDevice>().Display);
        container.Register<INetwork>(t => t.Resolve<IDevice>().Network);
    
        Resolver.SetResolver(container.GetResolver());
        #endregion
        ....
    }