Home > Software engineering >  How can I add code for iOS native only and call it when necessary in xamarin app?
How can I add code for iOS native only and call it when necessary in xamarin app?

Time:03-04

I am creating a demo project with xamarin and in that, I want to make a function which I can put in iOS native side and use that particular function when I needed and get a callback from the function from iOS native. I have checked but did not find any sufficient thing which can work with me. I want to call the below code for iOS only and need its response back to xamarin code.

 UIApplication.shared.open(redirectUrl, options: [:], completionHandler: { success in
    if success {
        // Handle success.
    } else {
        // Handle failure. Most likely app is not present on the user's device. You can redirect to App Store using these links:
       
    }
})

I am open to anything which can fix my issue for calling this function. If I can call it in xamarin then also please provide me suggestion so that I can put it in xamarin file.

CodePudding user response:

If I understand correctly , this could be achieved by Dependency Service .

Interface in Forms

public interface IMyService
{
   Task<bool> openUrl(string url);
}

Implementation in iOS

[assembly: Dependency(typeof(MyForms.iOS.MyService))]
namespace MyForms.iOS
{
    internal class MyService : IMyService
    {
        public Task<bool> openUrl(string url)
        {
            return UIApplication.SharedApplication.OpenUrlAsync(new NSUrl(url), null);
        }
    }
}

Usage in Forms

bool success = await DependencyService.Get<IMyService>().openUrl("www.google.com");
  • Related