gpt4 book ai didi

ios - 从目录中的所有 rtf 文件中读取文本并快速创建主文件

转载 作者:行者123 更新时间:2023-11-28 13:36:51 25 4
gpt4 key购买 nike

上下文我有一个应用程序,用户可以在其中编写多个“场景”。这些被保存为单独的文件。我需要为用户提供 2 个导出选项(将所有场景单独导出或全部导出到一个主文件中)。

我要做什么 目前我的方法是尝试检索每个扩展名为 .rtf 的文件的 URL。然后遍历每个,提取 NSAttributedString。最后,我计划将每个依次写入主 .rtf 文件。

我尝试了什么 使用来自其他各种答案的想法(例如 herehere 在类似的问题上我正在尝试下面我已经注释清楚的内容。不用说我我对下一步该做什么感到有点困惑和迷茫:

@IBAction func exportPressed(_ sender: Any) {
//THIS BIT RETRIEVES THE URLS OF EACH .RTF FILE AND PUTS THEM INTO AN ARRAY CALLED SCENEURLS. THIS BIT WORKS FINE AND I'VE TESTED BY PRINTING OUT A LIST OF THE URLS.

do {
let documentsURL = getDocumentDirectory()
let docs = try FileManager.default.contentsOfDirectory(at: documentsURL, includingPropertiesForKeys: [], options: [.skipsHiddenFiles, .skipsSubdirectoryDescendants])
let scenesURLs = docs.filter{ $0.pathExtension == "rtf" }

//THIS BIT TRYS TO RETURN THE NSATTRIBUTEDSTRING FOR EACH OF THE SCENE URLS. THIS BIT THROWS UP MULTIPLE ERRORS. I SUPPOSE I WOULD WANT TO ADD THE STRINGS TO A NEW ARRAY [SCENETEXTSTRINGS] SO I COULD THEN LOOP THROUGH THAT AND WRITE THE NEW MASTER FILE WITH TEXT FROM EACH IN THE RIGHT ORDER.

scenesURLs.forEach {_ in

return try NSAttributedString()(url: scenesURLs(),
options: [.documentType: NSAttributedString.DocumentType.rtf],
documentAttributes: nil)
} catch {

print("failed to populate text view with current scene with error: \(error)")

return nil
}
}
} catch {
print(error)
}

//THERE NEEDS TO BE SOMETHING HERE THAT THEN WRITES THE STRINGS IN THE NEW STRINGS ARRAY TO A NEW MASTER FILE
}

首先,我只需要一些关于如何获取数组中的字符串的帮助 - 之后我可以尝试编写新的 master!

最佳答案

如果你想要一个 NSAttributedString 的数组从文件 URL 数组中,您可以使用 map而不是 forEach .您还有几个语法问题需要修复。

替换您对 forEach 的使用与:

let attributedStrings = scenesURLs.compactMap { (url) -> NSAttributedString? in
do {
return try NSAttributedString(url: url, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
} catch {
print("Couldn't load \(url): \(error)")
return nil
}
}

如果您不关心记录错误,这可以简化为:

let attributedStrings = scenesURLs.compactMap {
return try? NSAttributedString(url: $0, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
}

创建一个 final NSAttributedString从数组中,你可以这样做:

let finalAttributedString = attributedStrings.reduce(into: NSMutableAttributedString()) { $0.append($1) }

关于ios - 从目录中的所有 rtf 文件中读取文本并快速创建主文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56497128/

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