fileExporter 是 SwiftUI 中用于保存文件(导出数据)的视图修饰器,和 fileImporter 是一对好搭档。
作用
fileExporter 会弹出一个系统保存对话框,允许用户选择:
1、文件保存的位置。
2、文件名称和类型。
3、是否替换已有文件(系统自动提示)。
需要提供一个符合 FileDocument 协议的数据模型(如 .txt、.json、.image 等),它就会自动保存为文件。
基本语法
.fileExporter(
isPresented: $showExporter,
document: MyDocument(),
contentType: .plainText,
defaultFilename: "myfile"
) { result in
// 保存结果处理
}
参数解析:
1、isPresented:Binding<Bool>类型,控制对话框是否显示。
2、document:FileDocument 实例,要导出的文档对象。
3、contentType:UTType类型,保存的文件类型(例如 .json, .png)。
4、defaultFilename:String?类型,默认文件名。
5、result:Result<URL, Error>类型,返回用户最终选择的文件位置或错误。
使用场景
导出文本文件
1、定义文档模型
import UniformTypeIdentifiers
import SwiftUI
struct MyTextDocument: FileDocument {
static var readableContentTypes: [UTType] { [.plainText] }
var text: String
init(text: String = "") {
self.text = text
}
init(configuration: ReadConfiguration) throws {
if let data = configuration.file.regularFileContents {
text = String(decoding: data, as: UTF8.self)
} else {
text = ""
}
}
func fileWrapper(configuration: WriteConfiguration) throws -> FileWrapper {
FileWrapper(regularFileWithContents: Data(text.utf8))
}
}
2、SwiftUI视图
struct FileExportView: View {
@State private var showExporter = false
@State private var exportText = "这是要保存的内容"
@State private var exportStatus = ""
var body: some View {
VStack(spacing: 20) {
Button("导出文件") {
showExporter = true
}
Text(exportStatus)
.font(.caption)
.foregroundColor(.gray)
}
.fileExporter(
isPresented: $showExporter,
document: MyTextDocument(text: exportText),
contentType: .plainText,
defaultFilename: "MyText"
) { result in
switch result {
case .success(let url):
exportStatus = "已保存到 \(url.lastPathComponent)"
case .failure(let error):
exportStatus = "保存失败:\(error.localizedDescription)"
}
}
}
}

导出文件后,返回保存成功信息。

关于FileDocument的知识,可以查看《SwiftUI文档类型协议FileDocument》进一步了解。
应用场景
1、保存用户生成的 Markdown 文本。
2、导出编辑后的 JSON 文件。
3、导出图像(如绘图结果)。
4、连续导出多个文件,通过循环触发。
总结
FileExporter是SwiftUI修饰符,通过弹出保存文件的系统对话框,实现保存文件的功能。
适配于iOS 14+、macOS 11+平台,可在非文档型App中快速实现导出功能。
相关文章
1、SwiftUI导入外部文件Fileimporter:https://fangjunyu.com/2025/07/05/swiftui%e5%af%bc%e5%85%a5%e5%a4%96%e9%83%a8%e6%96%87%e4%bb%b6fileimporter/
2、SwiftUI文档类型协议FileDocument:https://fangjunyu.com/2025/07/05/swiftui%e6%96%87%e6%a1%a3%e7%b1%bb%e5%9e%8b%e5%8d%8f%e8%ae%aefiledocument/