File System
Work with the app sandbox using FileManager, document directories, and data read/write APIs.
Locate Directories
Use FileManager to find the Documents and Caches folders.
Syntax: FileManager.default.urls(for:in:), e.g. .documentDirectory, .cachesDirectory
Example
Directories.swift
ContentView.swift
App.swift
import Foundation
let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let caches = FileManager.default.urls(for: .cachesDirectory, in: .userDomainMask).first!
print("Docs:", docs)
print("Caches:", caches)
This example locates the sandboxed Documents and Caches directories.
Read & Write
Write and read text or binary data using Data and String APIs.
Syntax:
try data.write(to: url)let data = try Data(contentsOf: url)try text.write(to: url, atomically:encoding:)
Example
ReadWrite.swift
ContentView.swift
App.swift
import Foundation
let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let file = docs.appendingPathComponent("hello.txt")
// Write text
let text = "Hello files!"
try? text.write(to: file, atomically: true, encoding: .utf8)
// Read text
let loaded = try? String(contentsOf: file, encoding: .utf8)
print(loaded ?? "")
This example writes a text file in Documents and reads it back.
Create and Remove
Create folders with createDirectory and delete entries with removeItem.
Syntax:
try FileManager.default.createDirectory(at:withIntermediateDirectories:)try FileManager.default.removeItem(at:)
Example
CreateRemove.swift
ContentView.swift
App.swift
import Foundation
let docs = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
let folder = docs.appendingPathComponent("Temp")
try? FileManager.default.createDirectory(at: folder, withIntermediateDirectories: true)
try? FileManager.default.removeItem(at: folder)
Leave a Reply