1

I'm loading .txt files onto a tableview and for the larger files, there is a lag of a noticeable second or 2 before the textview loads with the .txt file. Is there a way to quick load the first x number of lines immediately and then the rest of the file at the normal pace so I can get rid of that 1 second delay?

The files are in my bundle as .txt files.

They are loaded into UITableView like so:

let storyNames = [ "story7", "story3", "story4", "story8", "story11", "story9", "story12", "story2", "story5", "story6", "story1", "story10" ]

    let stories = storyNames.compactMap {
        story in
        return Bundle.main.url(forResource: storyName, withExtension: "txt")
    }

... tableview methods to print at cellForRowAt

Passed onto DetailTextView like:

override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
    if let vc = storyboard?.instantiateViewController(withIdentifier: "DetailTextView") as? DetailTextViewController {
        vc.selectedStory = stories[indexPath.row]
        navigationController?.pushViewController(vc, animated: true)
    }
}

And then printed in the DetailTextView:

let storyText = try? String(contentsOf: selectedStory)
    textView.text = storyText
bobcat
  • 177
  • 1
  • 12

2 Answers2

1

When you load the text file, make sure it's not running on the main thread:

    DispatchQueue.global().async {
        let storyText = try? String(contentsOf: selectedStory)
        DispatchQueue.main.async {
            textView.text = hymnText
        }
    }
janusfidel
  • 8,036
  • 4
  • 30
  • 53
  • Thank you. This gets rid of the view controller load lag, but there is still a slight lag in the textview loading of the text. Is there a way to pre load the first 10 or 12 lines so there isn't that time gap between blank textview and text shown? – bobcat Aug 21 '18 at 19:55
  • That will require a lot more work but it is possible using `NSFileHandle` . See https://stackoverflow.com/questions/3707427/how-to-read-data-from-nsfilehandle-line-by-line/3910036 – janusfidel Aug 21 '18 at 20:01
0

Why you not put in ViewWillDidAppear

override func viewDidAppear(_ animated: Bool) {
        let stories = storyNames.compactMap {
        story in
        return Bundle.main.url(forResource: storyName, withExtension: "txt")
    }
 }

And maybe you can put in same ViewController your detail, and only hidden your table, not? , with this you not open other ViewController or navigation. (sorry for my English)

Oh, too delete animated : navigationController?.pushViewController(vc, animated: false)

Maybe too , you can job with cache

var cache = NSCache<NSString, NSString>()

//if exist text

 if let text = cache.object(forKey: idText as NSString) {
            yourtext = text
        }else{
  let stories = storyNames.compactMap {
        story in
        return Bundle.main.url(forResource: storyName, withExtension: "txt")
       cache.setObject(stories, forKey: idText as NSString)

}

good luck!