简体   繁体   中英

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

Context I have an app where the user can write multiple 'scenes'. These are saved as separate file. I need to offer the user 2 options for exporting (to export all scenes individually or all together in one master file).

What am I try to do My approach at the moment is to try retrieve the URLs of each file with the extension of .rtf. Then to loop through each, extracting the NSAttributedString. Finally I plan on writing each in turn to a master .rtf file.

What have I tried Using ideas from various other answers (eg here and here on similar issues I am trying the below which I've annotated to make clear. Needless to say I am a bit stuck and lost for what to do next :

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

To start with, I just need some help with how to get the strings in an array - I can try work out writing the new master after that!

If you want an array of NSAttributedString from the array of file URLs, you can use map instead of forEach . You also have several syntax issues that need to be fixed.

Replace your use of forEach with:

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
    }
}

If you don't care about logging the error, this can be simplified to:

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

To create one final NSAttributedString from the array, you can do:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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