Swift

如何在iOS 11 App中显示Documents文件夹并与其他应用共享

1.info.plist里追加两个项目,值都是”YES”。

  • UIFileSharingEnabled (Application supports iTunes file sharing)
  • LSSupportsOpeningDocumentsInPlace (Supports opening documents in place)

2.修改代码。

  • 在程序加载时在Documents中创建App专属文件夹和文件。
  • 取得App专属文件夹里的文件名list。
import UIKit
import SwiftUI

class SceneDelegate: UIResponder, UIWindowSceneDelegate {

    var window: UIWindow?


    func scene(_ scene: UIScene, willConnectTo session: UISceneSession, options connectionOptions: UIScene.ConnectionOptions) {
        // Use this method to optionally configure and attach the UIWindow `window` to the provided UIWindowScene `scene`.
        // If using a storyboard, the `window` property will automatically be initialized and attached to the scene.
        // This delegate does not imply the connecting scene or session are new (see `application:configurationForConnectingSceneSession` instead).

        // 在Documents里创建App专属文件夹和文件
        let fm = FileManager.default
        let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true).first!
        let filePath = documentsPath + "/myfile.txt"
        if !fm.fileExists(atPath: filePath) {
            fm.createFile(atPath: filePath, contents: nil, attributes: [:])
        }
        
        // 文件名list取得
        let documentDirectoryURL = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)[0]
        var files = [""]
        do {
            let contentUrls = try FileManager.default.contentsOfDirectory(at: documentDirectoryURL, includingPropertiesForKeys: nil)
            files = contentUrls.map{$0.lastPathComponent}
            print(files) //-> ["test1.txt", "test2.txt"]
        } catch {
            print(error)
        }
        
        // Create the SwiftUI view that provides the window contents.
        // 将文件名list传给contentView
        let contentView = ContentView(filesNameList: files)

        // Use a UIHostingController as window root view controller.
        if let windowScene = scene as? UIWindowScene {
            let window = UIWindow(windowScene: windowScene)
            window.rootViewController = UIHostingController(rootView: contentView)
            self.window = window
            window.makeKeyAndVisible()
        }
    }

3.将App文件夹里的文件名显示在画面上。

4.验证导入文件,所以用iPhone手机测试。

5.第一次在手机上加载App,需要在手机上开权限。

6.这是程序启动后的画面,显示了App文件夹下的文件。

7.手机连接Macbook后,可以向App的文件夹里导入需要的文件。这样App就可以访问这些文件了。手机连接以后,需要先同步。