Saving and Loading Text in Swift

Swift 2.0
In this example we’ll assume there is a variable ‘score’ for saving the score of type Int and a HighScoreLabel to display it of type UILabel.

 

 

Here is a full solution on saving and loading text with Swift 2.0, current example is for saving and loading high score in a game.

Using those 2 functions we can now declare a variable to store a path to our highscore text file:

Here is how we would load  text from the file we now have :

Here is how we would compare the current score to the High Score and if bigger – we would save it :

Here is how we would load the High Score:

6 thoughts on “Saving and Loading Text in Swift

  1. I am quite new to this and I am for some reason having problems with the above. I really hope that you can help me with this problem.

    Before Xcode 7 (and Swift 2) this is what I used to load the text from a text file inside the documents directory to a label:

    func readFromDocumentsFile(fileName:String) -> String {

    let documentsPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0] as! NSString

    let path = documentsPath.stringByAppendingPathComponent(fileName)

    var checkValidation = NSFileManager.defaultManager()

    var error:NSError?

    var file:String

    if checkValidation.fileExistsAtPath(path) {

    file = NSString(contentsOfFile: path, encoding: NSUTF8StringEncoding, error: nil) as! String

    } else {

    file = “*ERROR* (fileName) does not exist.”

    }

    return file

    }

    And I could use it like this:

    label.txt = readFromDocumentsFile (“filename.txt”)

    And it was also working if the file was inside a subfolder

    label.txt = readFromDocumentsFile (“/subfolder/filename.txt”)

    How do I do the same thing now?

    / Peter

    • Razvigor Andreev says:

      So, basically you can no longer use ‘stringByAppendingPathComponent’ in Swift 2.0.
      You have to use NSURLs as I showed in the previous article. The only difference between mine and your example is that I have the methods broken down in separate functions and you have it all in one. Either way is should be fine, not a big difference. If you can’t figure it out I can try and rework your code a bit later today.

      • Yes, I would really appreciate it if you could rework the cod for me.

        Thank you

        / Peter

        • Razvigor Andreev says:

          No problem, here it is ( tested it on latest Xcode and it works) :

          func readFromDocumentsFile(fileName:String) -> String {

          let documentsPath = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]

          let path = documentsPath.URLByAppendingPathComponent(fileName).path!

          var error: NSError? = nil

          var file: String!

          do {

          file = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding)

          } catch let error1 as NSError {

          error = error1

          file = nil

          }

          if file == nil {

          print(“Error loading text from path: (path) error: (error?.localizedDescription)”)

          }

          print(“ReadFromDocumentsFile: (file)”)

          return file

          }

Leave a Reply

Your email address will not be published. Required fields are marked *