Use Droid project class in PCL Xamarin Forms

0

How do I use a class that was created in the project Droid in PCL ?

I've created a new class that will save the image to a folder in the project, but I need to call this class in PCL .

My class:

namespace PCI.APP.Droid
{
    public class SalvarFoto
    {
        public bool SalvarFotoPasta(string Imagem, string ImgNome)
        {
            try
            {
                String caminho = ConfigurationManager.AppSettings["ImageUsers"];

                if (!System.IO.Directory.Exists(caminho))
                {
                    System.IO.Directory.CreateDirectory(caminho);
                }

                string imagemNome = ImgNome + ".png";

                string imgPasta = Path.Combine(caminho, imagemNome);

                byte[] imageBytes = Convert.FromBase64String(Imagem);

                File.WriteAllBytes(imgPasta, imageBytes);

                return true;
            }
            catch (Exception ex)
            {
                throw ex;
            }
        }
    }
}
    
asked by anonymous 12.12.2016 / 14:30

1 answer

1

The most appropriate approach for this operation is to use Dependency Injection. The PCL should not have reference to the specific projects of each platform, to give a visibility of the same to the PCL we use the IjD. How to do?

1 - Create an interface called ISalvarFoto in your PCL and implement it in your droid project.

public interface ISalvarFoto 
{
     public bool SalvarFotoPasta(string Imagem, string ImgNome);
}

2 - Next, add the annotation to your assembly

[assembly: Dependecy(typeof(PCI.APP.Droid.SalvarFoto))]
namespace PCI.APP.Droid
{
   public class SalvarFoto : ISalvarFoto
   {
     ...
   }
}

3 - Now just request the implementation of the class. In the code snippet where you need the implementation of the class just do:

var salvarFoto = DependencyService.Get<ISalvarFoto>();

We request a class that implements the interface and as we mark the appropriate class the DependencyService is able to resolve and create the required instance.

    
17.12.2016 / 02:40