다음을 통해 공유


Xamarin.Essentials: 시작 관리자

Launcher 클래스를 사용하면 애플리케이션이 시스템을 통해 URI를 열 수 있습니다. 다른 애플리케이션의 사용자 지정 URI 체계에 대한 딥 링크를 설정할 때 주로 사용됩니다. 브라우저에서 웹 사이트를 열려면 Browser API를 참조해야 합니다.

시작하기

이 API를 사용하기 전에 라이브러리가 제대로 설치되고 프로젝트에 설정되어 있는지 확인하기 위해 Xamarin.Essentials에 대한 시작 가이드를 읽어보세요.

Launcher 사용

클래스에서 Xamarin.Essentials에 대한 참조를 추가합니다.

using Xamarin.Essentials;

Launcher 기능을 사용하려면 OpenAsync 메서드를 호출하고 열려는 string 또는 Uri를 전달합니다. 필요에 따라 CanOpenAsync 메서드를 사용하여 디바이스의 애플리케이션이 URI 스키마를 처리할 수 있는지 확인할 수 있습니다.

public class LauncherTest
{
    public async Task OpenRideShareAsync()
    {
        var supportsUri = await Launcher.CanOpenAsync("lyft://");
        if (supportsUri)
            await Launcher.OpenAsync("lyft://ridetype?id=lyft_line");
    }
}

그러면 매개 변수를 열 수 있는지 확인하고 열 수 있는 경우 여는 TryOpenAsync를 사용하여 단일 호출로 결합할 수 있습니다.

public class LauncherTest
{
    public async Task<bool> OpenRideShareAsync()
    {
        return await Launcher.TryOpenAsync("lyft://ridetype?id=lyft_line");
    }
}

추가 플랫폼 설정

추가 설정이 없습니다.

Files

이 기능을 사용하면 앱에서 다른 앱을 열고 파일을 볼 수 있도록 요청할 수 있습니다. Xamarin.Essentials는 자동으로 파일 형식(MIME)을 검색하고 파일을 열도록 요청합니다.

다음은 디스크에 텍스트를 작성하고 열도록 요청하는 샘플입니다.

var fn = "File.txt";
var file = Path.Combine(FileSystem.CacheDirectory, fn);
File.WriteAllText(file, "Hello World");

await Launcher.OpenAsync(new OpenFileRequest
{
    File = new ReadOnlyFile(file)
});

파일을 열 때의 프레젠테이션 위치

iPadOS에서 공유 또는 시작 관리자를 요청하는 경우 팝 오버 컨트롤에 표시할 수 있습니다. 이는 팝업이 표시되고 화살표가 직접 가리키는 위치를 지정합니다. 이 위치는 보통 작업을 시작한 컨트롤입니다. PresentationSourceBounds 속성을 사용하여 위치를 지정할 수 있습니다.

await Share.RequestAsync(new ShareFileRequest
{
    Title = Title,
    File = new ShareFile(file),
    PresentationSourceBounds = DeviceInfo.Platform== DevicePlatform.iOS && DeviceInfo.Idiom == DeviceIdiom.Tablet
                            ? new System.Drawing.Rectangle(0, 20, 0, 0)
                            : System.Drawing.Rectangle.Empty
});
await Launcher.OpenAsync(new OpenFileRequest
{
    File = new ReadOnlyFile(file),
    PresentationSourceBounds = DeviceInfo.Platform== DevicePlatform.iOS && DeviceInfo.Idiom == DeviceIdiom.Tablet
                            ? new System.Drawing.Rectangle(0, 20, 0, 0)
                            : System.Drawing.Rectangle.Empty
});

여기에 설명된 모든 내용은 ShareLauncher에 대해 동일하게 작동합니다.

Xamarin.Forms를 사용할 경우 View를 전달하고 경계를 계산할 수 있습니다.

public static class ViewHelpers
{
    public static Rectangle GetAbsoluteBounds(this Xamarin.Forms.View element)
    {
        Element looper = element;

        var absoluteX = element.X + element.Margin.Top;
        var absoluteY = element.Y + element.Margin.Left;

        // Add logic to handle titles, headers, or other non-view bars

        while (looper.Parent != null)
        {
            looper = looper.Parent;
            if (looper is Xamarin.Forms.View v)
            {
                absoluteX += v.X + v.Margin.Top;
                absoluteY += v.Y + v.Margin.Left;
            }
        }

        return new Rectangle(absoluteX, absoluteY, element.Width, element.Height);
    }

    public static System.Drawing.Rectangle ToSystemRectangle(this Rectangle rect) =>
        new System.Drawing.Rectangle((int)rect.X, (int)rect.Y, (int)rect.Width, (int)rect.Height);
}

RequestAsync 호출 시 이를 활용할 수 있습니다.

public Command<Xamarin.Forms.View> ShareCommand { get; } = new Command<Xamarin.Forms.View>(Share);
async void Share(Xamarin.Forms.View element)
{
    try
    {
        Analytics.TrackEvent("ShareWithFriends");
        var bounds = element.GetAbsoluteBounds();

        await Share.RequestAsync(new ShareTextRequest
        {
            PresentationSourceBounds = bounds.ToSystemRectangle(),
            Title = "Title",
            Text = "Text"
        });
    }
    catch (Exception)
    {
        // Handle exception that share failed
    }
}

Command 트리거 시 호출하는 요소를 전달할 수 있습니다.

<Button Text="Share"
        Command="{Binding ShareWithFriendsCommand}"
        CommandParameter="{Binding Source={RelativeSource Self}}"/>

플랫폼의 차이점

CanOpenAsync에서 반환된 작업이 즉시 완료됩니다.

API

Channel 9YouTube에서 더 많은 Xamarin 비디오를 확인하세요.