上下文 我有一个应用程序,用户可以在其中编写多个“场景”。这些文件另存为单独的文件。我需要为用户提供2个导出选项(将所有场景单独导出或全部导出到一个主文件中)。
我要做什么目前,我的方法是尝试检索扩展名为.rtf的每个文件的URL。然后遍历每个对象,提取NSAttributedString。最后,我计划依次将每个文件写入一个主.rtf文件。
我尝试过的事情在类似问题上使用其他答案(例如here和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{ $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
}
首先,我只需要一些如何获取数组中的字符串的帮助-之后,我可以尝试编写新的母版!
答案 0 :(得分:1)
如果要从文件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) }