You need to enable JavaScript to run this app. 在SwiftUI中导入文件后如何将导入的文件名保存为字符串?
优惠活动
大模型
产品
解决方案
定价
更多

在SwiftUI中导入文件后如何将导入的文件名保存为字符串?

SwiftUI 导入JSON文件并获取文件名、读取内容实现方案

首先需要在文件头部导入UniformTypeIdentifiers框架,.json类型定义在该框架中。

核心修改点

  • 新增两个状态变量,分别存储导入的文件名字符串和读取到的JSON内容
  • 在fileImporter回调中处理返回结果,依次完成安全权限申请、文件名提取、内容读取操作

完整可运行代码如下:

import SwiftUI
import UniformTypeIdentifiers

struct ContentView: View {
    @State var imported = false
    // 存储导入的文件名
    @State var fileName: String = ""
    // 存储读取到的JSON内容
    @State var jsonContent: String = ""
    
    var body: some View {
        VStack(spacing: 20) {
            Button(action: {imported.toggle()}, label: {
                Text("导入JSON文件")
            })
            
            // 展示文件名和内容
            if !fileName.isEmpty {
                Text("导入文件名:\(fileName)")
                    .font(.headline)
            }
            if !jsonContent.isEmpty {
                ScrollView {
                    Text(jsonContent)
                        .padding()
                }
                .frame(height: 300)
                .border(.gray)
            }
        }
        .padding()
        .fileImporter(isPresented: $imported, allowedContentTypes: [.json]) { res in
            do {
                // 获取选中的文件URL
                let fileUrl = try res.get()
                // 申请沙盒访问权限,否则沙盒环境下无法读取外部文件
                guard fileUrl.startAccessingSecurityScopedResource() else { return }
                
                // 获取带.json后缀的完整文件名,直接为String类型
                self.fileName = fileUrl.lastPathComponent
                // 如果需要无后缀的文件名,替换为下面的代码
                // self.fileName = fileUrl.deletingPathExtension().lastPathComponent
                
                // 读取JSON文件内容为字符串
                self.jsonContent = try String(contentsOf: fileUrl, encoding: .utf8)
                
                // 用完释放安全访问权限
                fileUrl.stopAccessingSecurityScopedResource()
            } catch {
                print("文件读取失败:\(error.localizedDescription)")
            }
        }
    }
}

struct ContentView_Previews: PreviewProvider {
    static var previews: some View {
        ContentView()
    }
}

内容的提问来源于stack exchange,提问作者geethsg7

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.19 05:06:11