简体   繁体   中英

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() {
    super.viewDidLoad()
    submitscorebtn.addTarget(self, action: "submitScore:", forControlEvents: UIControlEvents.TouchUpInside)
    print(score)

}

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

    print(text)

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

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

    }
}



}

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.

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