Home Ask Login Register

Developers Planet

Your answer is one click away!

colinmcp February 2016

swift: Writing to a file

Another swift question today. I'm trying to publish a users name and score to a textfile to compile a highscore list. I am using the writeToFile() function and am getting no errors, in my breakpoints the line is being reached and executed OK but I still see no changed reflected in my score.txt file. I should mention score.txt is included in the build path for the project...not sure if that changes anything, just thought I should mention it. Here is my code:

import Foundation
import UIKit

class victoryViewController : UIViewController
//  Define outputs
@IBOutlet weak var submitscorebtn: UIButton!

@IBOutlet weak var scorename: UITextField!

//  Define a string to hold the score value
var score = String()

//  Begin functions

override func viewDidLoad() {
    submitscorebtn.addTarget(self, action: "submitScore:", forControlEvents: UIControlEvents.TouchUpInside)


//Submit score to DB
func submitScore(sender: UIButton! )
    var text: String = scorename.text!
    text += ","
    text += score


    if let dir : NSString = NSSearchPathForDirectoriesInDomains(NSSearchPathDirectory.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first {
        let path = dir.stringByAppendingPathComponent("scores.txt");

        do {
            try text.writeToFile(path, atomically: false, encoding: NSUTF8StringEncoding)
        catch {print("Error writing score.")}




Nikolai Ruhe February 2016

Make sure you are looking at the proper file.

The file that you look at in Xcode is on your Mac, in your project directory. It is not the same file that the simulator or the iOS device writes to.

Finding the right file from Xcode is a bit complicated: Open the "Devices" view, select the device, select your app, open the cogwheel popup and select "Download Container..." and save it locally. Then you can inspect the contents of the Documents directory in the downloaded container and check the files contents with Xcode.

Post Status

Asked in February 2016
Viewed 1,476 times
Voted 4
Answered 1 times


Leave an answer

Quote of the day: live life