LoginSignup
1
2

More than 5 years have passed since last update.

Xamarin.Formsでファイルを受け取る(iOS編)

Last updated at Posted at 2017-02-24

Safariで開いたPDFをXamarin.Formsアプリで受け取るというのをやってみました。

screencast 2017-02-25 00-13-13.gif

まず、info.plistにPDFのドキュメントタイプを追加します。
これで、SafariでPDFを表示した時にアプリで開くためのメニューが表示されるようになります。

スクリーンショット 2017-02-24 23.36.12.jpg

スクリーンショット 2017-02-24 23.39.06.jpg

メニューからアプリが呼び出された時にOpenUrl(UIApplication app, NSUrl url, NSDictionary options)が呼び出されます。ここで、NSUrlのプロパティPathを引数にXamarin.FormsのAppのメソッドを呼び出します。

AppDelegate.cs
[Register("AppDelegate")]
public partial class AppDelegate : Xamarin.Forms.Platform.iOS.FormsApplicationDelegate
{
    App mainForms;
    public override bool FinishedLaunching(UIApplication app, NSDictionary options)
    {
        Xamarin.Forms.Forms.Init();

        mainForms = new App();

        LoadApplication(mainForms);

        return base.FinishedLaunching(app, options);
    }

    public override bool OpenUrl(UIApplication app, NSUrl url, NSDictionary options)
    {
        mainForms.DisplayThePDF(url.Path);

        return true;
    }
}

呼び出すメソッドで、PDFを表示する適当なページに遷移します。

App.xaml.cs
public partial class App : Application
{
  public void DisplayThePDF(string url)
  {
    var openFilePage = new OpenFilesPage(url);
    Application.Current.MainPage = openFilePage;
  }
}

受け取ったURIを煮るなり焼くなりすればいいです。自分はサンプルなので意味もなくWebViewで表示してみます。Safariから受け取る意味なくなるけど。。。

OpenFilePage.xaml.cs
public partial class OpenFilesPage : ContentPage
{
    public OpenFilesPage(string url)
    {
        var webView = new WebView
        {
            Source = url
        };
        Content = webView;
    }
}

参考:Sending Files to a Xamarin.Forms App – Part 1: iOS

1
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
2