且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

Flutter iOS文件共享-无法打开共享文件

更新时间:2023-09-15 16:16:52

最后找到了解决方法,并使用

Finally found a work around and got it working using this answer. What I ended up doing was opening the file in the app delegate, saving the file to the apps documents directory, then passing that url to the Flutter application. I opened the iOS module in xcode and changed the AppDelegate.swift to the following:

import UIKit
import Flutter

@UIApplicationMain
@objc class AppDelegate: FlutterAppDelegate {
override func application(
_ application: UIApplication,
didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]?
 ) -> Bool {
    GeneratedPluginRegistrant.register(with: self)
    return super.application(application, didFinishLaunchingWithOptions: launchOptions)
}

override func application(_ app: UIApplication, open url: URL, options: [UIApplication.OpenURLOptionsKey : Any] = [:]) -> Bool {
    var drawingFilename = ""
    do {
        let isAcccessing = url.startAccessingSecurityScopedResource()
        var error: Error? = nil
        let path = url.path
        
        let string = try String(contentsOf: url)
        drawingFilename = (url.path as NSString).lastPathComponent
        print(drawingFilename)
       
        let filename = getDocumentsDirectory().appendingPathComponent(drawingFilename)

        do {
            try string.write(to: filename, atomically: true, encoding: String.Encoding.utf8)
        } catch {
            // failed to write file – bad permissions, bad filename, missing permissions, or more likely it can't be converted to the encoding
        }
        if isAcccessing {
            url.stopAccessingSecurityScopedResource()
        }
      if #available(iOS 9.0, *) {
          return super.application(app, open: filename, options: options)
      } else {
         return false
      }
    } catch {
        print("Unable to load data: \(error)")
        return false
    }

    
      
}

func getDocumentsDirectory() -> URL {
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    return paths[0]
}
}

希望这对以后的人有帮助.

Hope this helps someone in the future.