简体   繁体   中英

creating a sdk for xamarin forms

All I have to do is create a library for Xamarin forms applications based on my native code(kotlin and swift). I created a multiplatform library and added platform-specific projects and a shared project. I also have two binding projects (one for Android and the other for iOS).

I'm trying to set up a DependencyService to invoke platform-specific code in a Multiplatform project so that I can use my library in an XF project.

When calling a DependencyService.Get<IService>() in the shared project I get null. (null reference exception)

I tried to register it like this: [assembly: Dependency (type (service))] - on top of the namespace declaration inside the iOS and Android projects, which I'm going to use in the XF project. I also tried to register the service in AppDelegate, but the error doesn't go away.

Here is an example of code that doesn't work: Interface in my shared project:

public interface IDevice
    {
        string GetInfo();
    }

This is an implementation of interface on the iOS:

[assembly: Xamarin.Forms.Dependency(typeof([path to namespace].DeviceService))]
namespace [path to namespace]
{
    public class DeviceService : IDevice
    {
        public string GetInfo()
        {
            return "some string";
        }
    }

}

A class with a method in a shared project that I will call from my XF project:

public class GrowDevice
    {
        static IDevice device;

        public GrowDevice()
        {
            DependencyService.Get<IDevice>();
        }

        public string GetInfo()
        {
            return device.GetInfo();
        }
    }

This is a code example of how I will call the GetInfo() method which is in the multiplatform library in a shared project, from my xamarin.froms project:

public ICommand GetDeviceInfoCommand => new Command(async () => { await GetInfo(); });

       
        private async Task GetInfo()
        {
            var grow = new [path to class].GrowDevice();
            Device = grow.GetInfo();
        }

How can I call platform specific code in the iOS project from the Shared project with DependencyService? Or maybe there is some other way?

You should assignment the result of the DependencyService.Get() to the staic variable which you have declared.

public class GrowDevice
{
    static IDevice device;

    public GrowDevice()
    {
       device = DependencyService.Get<IDevice>();
    }

    public string GetInfo()
    {
        return device.GetInfo();
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM