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.
1 2 3 4 5 6 7 8 9 10 11 |
func getDocumentsURL() -> NSURL { let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0] return documentsURL } func fileInDocumentsDirectory(filename: String) -> String { let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename) return fileURL.path! } |
Using those 2 functions we can now declare a variable to store a path to our highscore text file:
1 |
let scoreSavePath = fileInDocumentsDirectory("highScore.txt") |
Here is how we would load text from the file we now have :
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
func loadTextFromPath(path: String) -> String? { var error: NSError? = nil let text: String? do { text = try String(contentsOfFile: path, encoding: NSUTF8StringEncoding) } catch let error1 as NSError { error = error1 text = nil } if text == nil { print("Error loading text from path: \(path) error: \(error?.localizedDescription)") } return text } |
Here is how we would compare the current score to the High Score and if bigger – we would save it :
1 2 3 4 5 6 7 8 9 10 11 12 13 |
func saveHighScore() { print("Trying to save current High Score of: \(score)") if let savedHighScore = loadTextFromPath(scoreSavePath) { if score > Int(savedHighScore) { print("Our score of: \(score) is bigger than the saved HS of: \(savedHighScore)") saveText("\(score)", path: scoreSavePath ) } } else { saveText("\(score)", path: scoreSavePath ) } } |
Here is how we would load the High Score:
1 2 3 4 5 6 7 8 |
func loadHighScore() { if let savedHighScore = loadTextFromPath(scoreSavePath) { HighScoreLabel.text = ("High Score: \(savedHighScore)") print("\(savedHighScore)") } } |
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
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
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
}
Thank You!
It works perfectly 🙂
/ Peter
Great ! 🙂 Good luck !