[英]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.