Search code examples
androidiosxamarinxamarin.iosxamarin.android

How to open default browser in Xamarin?


I would like to open a web page in Xamarin for both Android and iOS but the code wouldn't work. Can anyone help me figure out what's wrong?

For Android, clicking the button goes through the code, but nothing happens afterward. For iOS, clicking the button does open a Safari page, but it cannot open the page, and displays a message "Safari could not open the page because the server stopped responding."

The test arg passed is: "http://www.google.com"

Thanks.

Code:

    async Task ExecuteLaunchBrowserAsync(string arg)
    {
        if (IsBusy)
            return;

        try
        {
            await CrossShare.Current.OpenBrowser(arg, new BrowserOptions
            {
                ChromeShowTitle = true,
                ChromeToolbarColor = new ShareColor
                {
                    A = 255,
                    R = 100,
                    G = 50,
                    B = 255
                },
                UseSafariReaderMode = true,
                UseSafariWebViewController = true
            });
        }
        catch
        {
        }
    }

Solution

  • You just need to use blow code, it will work for both Android and iOS.

    void Device.OpenUri(Uri uri)
    

    eg.

    Device.OpenUri(new Uri("http://example.com"))
    

    To work in iOS use Transport security in Info.plist

    <key>NSAppTransportSecurity</key>
    <dict>
        <key>NSAllowsArbitraryLoads</key><true/>
    </dict>
    

    https://i.sstatic.net/bsaQm.gif