Xamarin Forms 中的 UIDocumentPickerViewController 选择

UIDocumentPickerViewController selection in Xamarin Forms

我无法让我的 DocumentPicker 正常工作。现在它显示了视图控制器,但我不知道如何等待或获得结果。

在 swift 中,您只需编写 void documentPicker(UIDocumentPickerViewController controller, didPickDocumentAtUrl... 方法,当它完成时,它会转到那里。

但在Xamarin中肯定没那么简单。我已经从 class 以及我的 AppDelegate.cs class 和我的 Main.cs [=25= 中调用了该方法]. None 似乎有效,除非我写错了。

我有的是这个....

public async Task<string> pickResume()
{
    string path = string.Empty;

    var controller = new UIViewController();
    var docVC = new UIDocumentPickerViewController(new string[] { "org.openxmlformats.wordprocessingml.document", "com.microsoft.word.doc" }, UIDocumentPickerMode.Import);
    UIViewController topController = getTopViewController();
    topController.PresentViewController(docVC, true, null); 

    return path;
}

 void documentPicker(UIDocumentPickerViewController controller, NSUrl didPickDocumentAtURL)
 {
     Console.WriteLine("done"); 
 }

getTopViewController() 只是获取顶视图控制器的辅助方法,因此我可以显示 DocumentPicker

想通了,这比我想象的要容易得多。

UIDocumentPickerViewController 有两个 EventHandlersDidPickDocumentWasCancelled,所以我只是将它们分配给两个不同的方法并完成。

public async Task<string> pickResume()
{
    string path = string.Empty;
    var controller = new UIViewController();

    var docVC = new UIDocumentPickerViewController(new string[] { "org.openxmlformats.wordprocessingml.document", "com.microsoft.word.doc" }, UIDocumentPickerMode.Import);
    docVC.DidPickDocument += DocVC_DidPickDocument;
    docVC.WasCancelled += DocVC_WasCancelled;

    UIViewController topController = getTopViewController();
    topController.PresentViewController(docVC, true, null); 

    return await GetDocPath(new CancellationTokenSource());
}

private void DocVC_WasCancelled(object sender, EventArgs e)
{
    //Handle being cancelled 
}

private void DocVC_DidPickDocument(object sender, UIDocumentPickedEventArgs e)
{
    //Handle document selection
}