Use Droid project class in PCL Xamarin Forms

Asked

Viewed 127 times

0

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

I created a new class that will save the image in a folder in the project, but I need to call this class 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;
            }
        }
    }
}

1 answer

1


The most correct approach to 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 for the PCL we use the Ijd. How to do?

1 - Create an interface called Isalvarphoto on your PCL and implement it on your Droid project.

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

2 - Next, add note 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 want a class that implements the interface and how we mark the appropriate class Dependencyservice is able to solve and create the required instance.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.