如何观察共享应用程序组文件已更改

How to observe shared app groups file changed

我有一个在我的应用程序和扩展程序之间共享的文件: 从扩展名写入文件:

func writeToFile()
{
    let file = "file.txt" 
    let text = "data" //just a text
    let dir = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.ml.test.apps")!

        let fileURL = dir.appendingPathComponent(file)
        do {
            try text.write(to: fileURL, atomically: false, encoding: .utf8)
        }
        catch {/* error handling here */}

    }

从应用读取:

func readFromFile()
{
    let file = "file.txt"
    let dir = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.ml.test.apps")!

        let fileURL = dir.appendingPathComponent(file)
        do {
            let text2 = try String(contentsOf: fileURL, encoding: .utf8)
            NSLog("Dan: \(text2)")
        }
        catch {/* error handling here */}
    }

我的问题是如何观察此文件的更改。如果扩展写入它并更改数据,那么应用程序将收到通知更改并读取文件。

这是一个基于用法 NSFileCoordinator/NSFilePresenter 模式的方法的简单演示。

测试 Xcode 11.4 / iOS 13.4

  1. 申请部分。这里有一个 ViewController 扮演文件展示者的角色,为简单起见(如果一个控制器可以管理许多文件,那么最好为每个文件创建明确的展示者)
class ViewController: UIViewController, NSFilePresenter {
    var presentedItemURL: URL?
    var presentedItemOperationQueue: OperationQueue = OperationQueue.main


    @IBOutlet weak var userNameField: UILabel!

    func presentedItemDidChange() { // posted on changed existed file only
        readFromFile()
    }

    override func viewWillAppear(_ animated: Bool) {
        super.viewWillAppear(animated)

        // register for presentedItemDidChange work 
        NSFileCoordinator.addFilePresenter(self) 
    }

    override func viewWillDisappear(_ animated: Bool) {
        super.viewWillDisappear(animated)

        // unregister - required !!
        NSFileCoordinator.removeFilePresenter(self) 
    }

    override func viewDidLoad() {
        super.viewDidLoad()

        let file = "file.txt"
        let dir = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.test.apps")!
        presentedItemURL = dir.appendingPathComponent(file)

        readFromFile() // read previously stored data
    }

    private func readFromFile()
    {
        let coordinator = NSFileCoordinator(filePresenter: self)
        coordinator.coordinate(readingItemAt: presentedItemURL!, options: [], error: nil) { url in
            if let text2 = try? String(contentsOf: url, encoding: .utf8) {
                userNameField.text = text2 // demo label in view for test
            } else {
                userNameField.text = "<no text>"
                //just initial creation of file needed to observe following changes
                coordinator.coordinate(writingItemAt: presentedItemURL!, options: .forReplacing, error: nil) { url in
                    do {
                        try "".write(to: url, atomically: false, encoding: .utf8)
                    }
                    catch { print("writing failed") }
                }
            }
        }
    }
}
  1. 扩展部分(一键演示的简单 Today 扩展)
class TodayViewController: UIViewController, NCWidgetProviding, NSFilePresenter {
    var presentedItemURL: URL?
    var presentedItemOperationQueue: OperationQueue = OperationQueue.main

    override func viewDidLoad() {
        super.viewDidLoad()

        let file = "file.txt"
        let dir = FileManager.default.containerURL(forSecurityApplicationGroupIdentifier: "group.com.test.apps")!
        presentedItemURL = dir.appendingPathComponent(file)
    }
        
    @IBAction func post(_ sender: Any) { // action on button in extension
        writeToFile()
    }

    func writeToFile()
    {
        let text = "new data" //just a text
        let coordinator = NSFileCoordinator(filePresenter: self)
        coordinator.coordinate(writingItemAt: presentedItemURL!, options: .forReplacing, error: nil) { url in
            do {
                try text.write(to: url, atomically: false, encoding: .utf8)
            }
            catch { print("writing failed") }
        }
    }

    func widgetPerformUpdate(completionHandler: (@escaping (NCUpdateResult) -> Void)) {
        completionHandler(NCUpdateResult.newData)
    }
    
}

backup