Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> iOS

วิธีสร้างไฟล์ เขียนข้อมูล และอ่านข้อมูลบน iOS (File I/O)

File I/O บน iOS: สร้าง เขียน อ่าน ไฟล์ใน Documents Directory

ใช้ FileManager และ String.write(to:atomically:encoding:) จัดการไฟล์ Text ได้ง่าย

ขั้นตอนที่ 1: สร้างโปรเจกต์

Xcode → Single View App → ชื่อ "ReadingWritingFile"

ขั้นตอนที่ 2: ฟังก์ชันสร้าง เขียน อ่าน ไฟล์

func createReadAndWriteFile() {
    // 1. หา Documents Directory URL
    let fileName = "sample"
    let documentsURL = try! FileManager.default.url(
        for: .documentDirectory,
        in: .userDomainMask,
        appropriateFor: nil,
        create: true
    )
    let fileURL = documentsURL
        .appendingPathComponent(fileName)
        .appendingPathExtension("txt")
    
    print("File path: \(fileURL.path)")
    
    // 2. เขียนข้อมูล
    let stringData = "Hello Tutorials Point."
    do {
        try stringData.write(to: fileURL, atomically: true, encoding: .utf8)
        print("Write success")
    } catch {
        print("Write error: \(error)")
    }
    
    // 3. อ่านข้อมูล
    do {
        let readString = try String(contentsOf: fileURL, encoding: .utf8)
        print("Read content: \(readString)")
    } catch {
        print("Read error: \(error)")
    }
}

ขั้นตอนที่ 3: เรียกใน viewDidLoad

override func viewDidLoad() {
    super.viewDidLoad()
    createReadAndWriteFile()
}

รันและตรวจสอบ

  1. Run บน Simulator
  2. ดู Console: จะแสดง File Path (เช่น /Users/.../Documents/sample.txt)
  3. เปิด Finder → Cmd+Shift+G → วาง Path → จะเจอไฟล์ sample.txt

ขยายความสามารถ

เขียน Struct/Codable Object (JSON)

struct User: Codable {
    let name: String
    let age: Int
    let email: String
}

func saveUser(_ user: User) {
    let encoder = JSONEncoder()
    encoder.outputFormatting = .prettyPrinted
    let data = try! encoder.encode(user)
    try! data.write(to: fileURL)
}

func loadUser() -> User? {
    let data = try! Data(contentsOf: fileURL)
    return try! JSONDecoder().decode(User.self, from: data)
}

Append ข้อมูล (ไม่ทับไฟล์เดิม)

func appendToFile(_ text: String) {
    let handle = try! FileHandle(forWritingTo: fileURL)
    handle.seekToEndOfFile()
    handle.write(text.data(using: .utf8)!)
    handle.closeFile()
}

จัดการ Error อย่างเหมาะสม (Production Code)

enum FileError: Error {
    case writeFailed(Error)
    case readFailed(Error)
    case fileNotFound
}

func safeWrite(_ text: String) throws {
    do {
        try text.write(to: fileURL, atomically: true, encoding: .utf8)
    } catch {
        throw FileError.writeFailed(error)
    }
}

Documents Directory vs อื่นๆ

DirectoryUse CaseBackup iCloud
DocumentsUser Data, Exported Files✅ Yes
Library/CachesCache, Temp Download❌ No
tmp (NSTemporaryDirectory)Short-lived Temp Files❌ No (Auto-clean)
Library/Application SupportApp Internal Data (DB, Config)✅ Yes

Debug Tip: เปิดไฟล์ใน Simulator

// ใน viewDidLoad เพิ่ม:
print("📁 Documents: \(documentsURL.path)")
// Copy Path → Finder → Cmd+Shift+G → Paste → Enter
No