繁体   English   中英

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

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

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

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

我尝试了什么使用其他各种答案的想法(例如, 在这里这里就类似的问题,我正在尝试以下我已经注释过的问题。不用说,我对下一步的工作感到困惑和迷茫:

@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!

如果要从文件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: $0, options: [.documentType: NSAttributedString.DocumentType.rtf], documentAttributes: nil)
}

要从数组创建一个最终的NSAttributedString ,可以执行以下操作:

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM