.documentDirectory
๐ ๅ่๏ผSwift Playgrounds โฉ Image Gallery (Data Model: Gathering Image URLs)
import Foundation
extension FileManager {
/// URL of the app's document directory.
var documentDirectory: URL? {
urls(for: .documentDirectory, in: .userDomainMask).first
}
}
๐ ๅ่๏ผPaul โฉ Writing data to the documents directory
struct ContentView: View {
var body: some View {
VStack {
Text("Hello World").onTapGesture {
// ๐ FileManager + .documentDirectory
guard let dir = FileManager.default.documentDirectory else {
fatalError("No Documents directory!")
}
// โญ๏ธ path to `Documents/message.txt`
let url = dir.appendingPathComponent("message.txt")
do {
let str = "Test Message"
// โญ๏ธ write: String -> file (UTF8 encoded)
try str.write(to: url, atomically: true, encoding: .utf8)
// โญ๏ธ read: file -> String (UTF8 decoded?)
let msg = try String(contentsOf: url)
print(msg) // "Test Message"
} catch {
print(error.localizedDescription)
}
}
}.padding()
}
}
Foundation โฉ NSString โฉ
ๅ๏ผใ
urls(for: .documentDirectory, in: .userDomainMask).first
ๆๅฏ่ฝๆฏ nil
ๅโ
ใ
๐ StackOverflow
Last updated