iOS 14: NSFilePresenter не получает обратных вызовов / уведомлений; работает на iOS13

#icloud #ios14 #icloud-drive #nsfilecoordinator #nsfilepresenter

#icloud #ios14 #icloud-drive #nsfilecoordinator #nsfilepresenter

Вопрос:

У меня есть UIViewController, который использует протокол NSFilePresenter. Я внедрил presentedItemDidChange(), чтобы получать изменения файлов, хранящихся в повсеместном контейнере в iCloud. Моя реализация работает нормально на iOS13.7, но не работает на iOS 14.

Когда я изменяю представленные файлы из внешнего процесса, такого как «Finder» на macOS, presentedItemDidChange() НЕ вызывается.

Если это известная ошибка в iOS 14 или я что-то упустил в своей реализации?

Моя реализация выглядит примерно так:

 var m_basename = "textfile.txt"

var iCloudURL: URL?  {
  get {
    guard let iCloudDocumentsBaseURL = FileManager.default.url(forUbiquityContainerIdentifier: iCloudContainerId) else {
      return nil
    }
    let iCloudDocumentsURL = iCloudDocumentsBaseURL.appendingPathComponent("Documents").appendingPathComponent(m_basename)
    return iCloudDocumentsURL
  }
}

override func viewDidLoad() {
  super.viewDidLoad()
  // Do any additional setup after loading the view.
  
  NSFileCoordinator.addFilePresenter(self)

  /* do some iCloud availability check here ; not shown */

  save(text: "Test string") { (success) in
    if success {
      print(#function, "Wrote file successfully")
    } else {
      print(#function, "Write file failed")
    }
  }
}

public func save(text: String, completion: @escaping (Bool) -> Void) {
  if let presenterurl = self.presentedItemURL {
    var errorMain: NSError?

    // set presenter if we load a file that is currently being presented
    var filePresenter: NSFilePresenter? = nil
    if presenterurl == iCloudURL {
      filePresenter = fPresenter
    }

    let coord = NSFileCoordinator(filePresenter: filePresenter)
    coord.coordinate(writingItemAt: activeURL, options: .forReplacing, error: amp;errorMain) { (writeUrl) in
      do {
        try text.write(toFile: writeUrl.path, atomically: true, encoding: String.Encoding.utf8)
        print(#function, "(writeUrl) write OK")
        completion(true)
      } catch {
        print(#function, "(writeUrl) write failed: (error.localizedDescription)")
        completion(false)
      }
    }
    if errorMain != nil {
      print("Error: ", errorMain!.localizedDescription)
      completion(false)
    }
  }
  print(#function, "end of save() function")
}

// MARK: - NSFilePresenter
extension ViewController: NSFilePresenter {
  public var presentedItemURL: URL? {
      return iCloudURL
  }
  
  public var presentedItemOperationQueue: OperationQueue {
    return OperationQueue.main
  }
  
  public func presentedItemDidChange() {
    print(#function, "Loading file (m_basename)")
  }
}
  

Спасибо

Комментарии:

1. Возникает та же проблема.

2. В настоящее время я общаюсь с инженерами Apple, но они по-прежнему отказываются признавать существование этой ошибки. Пожалуйста, отправьте сообщение об ошибке и отправьте TSI в Apple, чтобы заставить их поверить в наличие проблемы. Спасибо