You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Swift 3 + Xcode 9.3:如何将日期时间追加写入文件而非覆盖

Append Date/Time to a Log File (Swift 3 + Xcode)

Hey! I get it—when you're just starting out with Swift 3 and Xcode, finding code that appends to a file (instead of overwriting everything) can be a bit confusing. Let's walk through a straightforward implementation that adds the current date and time to a log file every time your button is tapped.

Step 1: Get a Safe File Path

iOS limits where you can save files, so we'll use the app's Documents directory—it's persistent and accessible. Add this helper function to your view controller:

func getLogFileURL() -> URL? {
    // Get the path to the app's Documents folder
    guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, 
                                                            in: .userDomainMask).first else {
        print("Couldn't access the Documents directory")
        return nil
    }
    // Append a filename (we'll use "app_logs.txt")
    return documentsDirectory.appendingPathComponent("app_logs.txt")
}

Step 2: Create the Button Tap Action

Connect your button to an IBAction in your view controller (control-drag from the button to your code). Then add this logic to handle the append:

@IBAction func logDateTimeButtonTapped(_ sender: UIButton) {
    // 1. Format the current date/time into a readable string
    let dateFormatter = DateFormatter()
    dateFormatter.dateFormat = "yyyy-MM-dd HH:mm:ss" // Customize this to your preferred format
    let logEntry = "\(dateFormatter.string(from: Date()))\n" // Add a newline for clean logs
    
    // 2. Get the log file URL
    guard let logFileURL = getLogFileURL() else { return }
    
    // 3. Append the entry to the file (or create it if it doesn't exist)
    do {
        // Try to open the file in write mode (for appending)
        let fileHandle = try FileHandle(forWritingTo: logFileURL)
        // Move the file pointer to the end of the file (so we don't overwrite existing content)
        fileHandle.seekToEndOfFile()
        // Convert the log string to data and write it
        if let logData = logEntry.data(using: .utf8) {
            fileHandle.write(logData)
        }
        // Close the file handle
        fileHandle.closeFile()
    } catch let error as NSError where error.code == NSFileNoSuchFileError {
        // If the file doesn't exist yet, create it and write the first entry
        do {
            try logEntry.write(to: logFileURL, atomically: true, encoding: .utf8)
        } catch {
            print("Error creating initial log file: \(error.localizedDescription)")
        }
    } catch {
        // Catch any other errors
        print("Error appending to log file: \(error.localizedDescription)")
    }
}

Quick Customization Tips

  • Change the date format: Modify the dateFormat string to match your needs. For example, "MM/dd/yyyy hh:mm a" gives you 12-hour time with AM/PM.
  • Add extra context: Update the logEntry string to include more info, like "\(dateFormatter.string(from: Date())) - User tapped the log button\n".
  • Check the log file: To verify the file is being written, use Xcode's "Devices and Simulators" window (Window > Devices and Simulators), select your app, click "Download Container", then browse to the Documents folder to find app_logs.txt.

This code ensures every button tap adds a new line to your log file—no overwriting existing entries, exactly what you need!

内容的提问来源于stack exchange,提问作者John Martin

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:21:24