从目录中的所有 rtf 文件中读取文本并创建主文件 swift

Read text from all rtf files in directory and create master file swift

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

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

我尝试了什么 使用来自其他各种答案的想法(例如 and here 在类似的问题上我正在尝试下面我已经注释清楚的内容。不需要可以说我有点不知所措,不知道下一步该怎么做 :

@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{ [=11=].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
    }

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

如果您想要文件 URL 数组中的 NSAttributedString 数组,您可以使用 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: [=11=], options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
}

要从数组创建一个最终的 NSAttributedString,您可以这样做:

let finalAttributedString = attributedStrings.reduce(into: NSMutableAttributedString()) { [=12=].append() }