Fix main-thread blocking I/O

This commit is contained in:
世界
2026-02-05 02:37:02 +08:00
parent 4ae421cd04
commit 2e682d746c
17 changed files with 643 additions and 237 deletions
+35
View File
@@ -2,6 +2,9 @@ import Foundation
public extension Profile {
func read() throws -> String {
#if DEBUG
precondition(!Thread.isMainThread, "Profile.read() must not be called on the main thread")
#endif
switch type {
case .local, .remote:
return try String(contentsOfFile: path)
@@ -12,6 +15,9 @@ public extension Profile {
}
func write(_ content: String) throws {
#if DEBUG
precondition(!Thread.isMainThread, "Profile.write(...) must not be called on the main thread")
#endif
switch type {
case .local, .remote:
try content.write(toFile: path, atomically: true, encoding: .utf8)
@@ -20,4 +26,33 @@ public extension Profile {
try content.write(to: saveURL, atomically: true, encoding: .utf8)
}
}
func readAsync() async throws -> String {
let type = type
let path = path
return try await BlockingIO.run {
switch type {
case .local, .remote:
return try String(contentsOfFile: path)
case .icloud:
let saveURL = FilePath.iCloudDirectory.appendingPathComponent(path)
return try String(contentsOf: saveURL)
}
}
}
func writeAsync(_ content: String) async throws {
let type = type
let path = path
let content = content
try await BlockingIO.run {
switch type {
case .local, .remote:
try content.write(toFile: path, atomically: true, encoding: .utf8)
case .icloud:
let saveURL = FilePath.iCloudDirectory.appendingPathComponent(path)
try content.write(to: saveURL, atomically: true, encoding: .utf8)
}
}
}
}