gpt4 book ai didi

ios - 在 UIActivityItemProvider 中动态创建 UIDocument

转载 作者:行者123 更新时间:2023-11-28 23:33:56 25 4
gpt4 key购买 nike

我正在使用 Core Data 来存储我的用户数据。我想在 UI 中提供一个共享按钮,以便将数据导出到他们想要的任何地方。我制作了一个符合 UIActivityItemSource 的类。如果它只是从 activityViewController:itemForActivityType 返回一个 Data 对象,但该文件具有系统提供的文件名,则它是成功的。因此,我现在正在尝试动态生成一个 UIDocument,将其保存到文件系统,然后返回 URL(UIDocument.fileURL) 到事件 View Controller 。问题是 UIDocument.save 是异步的,但在保存文件之前我无法从 activityViewController:itemForActivityType 返回。我的最新代码如下所示:

类初始化:

let saveQueue = DispatchQueue(label: "saveQueue")
let saveSemaphore = DispatchSemaphore(value: 0)

...

func activityViewController(_ activityViewController: UIActivityViewController, itemForActivityType activityType: UIActivity.ActivityType?) -> Any? {
var success = false
self.saveQueue.async {
self.document.save(to: self.document.fileURL,
for: .forOverwriting) {(didSucceed) in
success = didSucceed
self.saveSemaphore.signal()
}
}
saveSemaphore.wait()
return success ? document.fileURL : nil
}

行为是异步代码启动,但永远不会调用保存的完成函数。我做错了什么?


根据 Casey 的帮助,我的最终解决方案是覆盖 UIDocument.save

override func save(to url: URL, for saveOperation: UIDocument.SaveOperation, completionHandler: ((Bool) -> Void)? = nil) {
do {
let contents = try self.contents(forType: GlobalConst.exportType) as! Data
try contents.write(to: url, options: [.atomicWrite])
completionHandler?(true)
} catch {
print("write error: \(error)")
completionHandler?(false)
}
}

我还不明白为什么父类(super class)保存是个问题,但我可以让它溜走。

最佳答案

为了让它工作,我必须创建 UIDocument 的子类并覆盖 func save(to:for:completionHandler:)

class MyDocument: UIDocument {

var body: String = "Hello world, this is example content!"

override func save(to url: URL, for saveOperation: UIDocument.SaveOperation, completionHandler: ((Bool) -> Void)? = nil) {
do {
try self.body.write(toFile: url.path, atomically: true, encoding: .utf8)
completionHandler?(true)
} catch {
print("write error: \(error)")
completionHandler?(false)
}
}
}

您的代码保持完全相同,只需确保 self.document 的类型为 MyDocument (或您可能已经拥有的任何子类)。

let document = MyDocument(fileURL: URL(fileURLWithPath: NSHomeDirectory() + "/Documents/output.txt"))

关于ios - 在 UIActivityItemProvider 中动态创建 UIDocument,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55697625/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com