flutter 从外部打开文件,例如在 ios 上“打开”

las*_*ink 5 android external-application file ios flutter

据我所知,大多数 flutter 指南都可以从本地存储打开,但没有关于文件共享的信息。任何人都知道如何做到这一点。这是专门针对 ios 启用它的指南https://developer.apple.com/library/archive/qa/qa1587/_index.html

我的意思是有https://pub.dartlang.org/packages/open_file扩展名,但从文件存储中打开。

要澄清这个问题并不是要与另一个应用程序共享文件,而是当从外部应用程序共享时,系统会提示在此flutter应用程序中打开文件。

小智 1

要在 iOS 中执行此操作,您首先按照您提到的指南中的描述在 XCode 中定义文档类型和导入的 UTI,然后在 AppDelegate.m 文件中执行以下操作:

- (BOOL)application:(UIApplication *)application
    didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

    /* custom code begin */
    FlutterViewController* controller = (FlutterViewController*)self.window.rootViewController;
    FlutterMethodChannel* myChannel = [FlutterMethodChannel
                                          methodChannelWithName:@"my/file"
                                          binaryMessenger:controller];
    __block NSURL *initialURL = launchOptions[UIApplicationLaunchOptionsURLKey];

    [myChannel setMethodCallHandler:^(FlutterMethodCall* call, FlutterResult result) {
        if ([@"checkintent" isEqualToString:call.method]) {
            if (initialURL) {
                [myChannel invokeMethod:@"loaded" arguments: [initialURL absoluteString]];
                initialURL = nil;
                result(@TRUE);
            }
        }
    }];
    /* custom code end */

    [GeneratedPluginRegistrant registerWithRegistry:self];
    // Override point for customization after application launch.
    return [super application:application didFinishLaunchingWithOptions:launchOptions];
}
Run Code Online (Sandbox Code Playgroud)

在 Dart 方面:

class PlayTextPageState extends State<MyHomePage> with WidgetsBindingObserver{
  static const platform = const MethodChannel('my/file');

  void initState() {
    super.initState();

    WidgetsBinding.instance.addObserver(this);

    platform.setMethodCallHandler((MethodCall call) async {
      String method = call.method;

      if (method == 'loaded') {
        String path = call.arguments; // this is the path
        ...
      }
    });
  }

  @override
  void didChangeAppLifecycleState(AppLifecycleState state) {
    super.didChangeAppLifecycleState(state);

    if (state == AppLifecycleState.paused) {
      ...
    } else if (state == AppLifecycleState.resumed) {
      platform.invokeMethod("checkintent")
        .then((result) {
          // result == 1 if the app was opened with a file
        });
    }
  }
}
Run Code Online (Sandbox Code Playgroud)