iphone - 在 iphone 中使用 swift 读取文件
问题描述
我需要在我的 iphone 中使用 swift 读取文件。在我的计算机中,我使用此代码并正常运行。文件“test.txt”在我的桌面中。
import UIKit
class Controller: UIViewController {
override func viewDidLoad() {
super.viewDidLoad()
// Do any additional setup after loading the view.
let sourcePath = URL(fileURLWithPath: "/Users/myname/Desktop", isDirectory: true)
let file : URL = URL(fileURLWithPath: "test.txt", relativeTo: sourcePath)
let filemgr = FileManager.default
if filemgr.fileExists(atPath: file.path){
do{
//Code to Parse text
} catch let error as NSError{
print ("Error: \(error)")
}
}
}
}
问题是我需要在我的 iphone 中读取这个文件。但我不知道哪个是读取文件的 URL。我可以在哪里保存文件,哪个是 URL?
谢谢
解决方案
1-将文本文件拖到项目中并选择copy Items If needed
2-用这个来阅读它
do {
if let path = Bundle.main.path(forResource: "fileName", ofType: "txt") {
let str = try String(contentsOfFile:path, encoding: .utf8)
print(str)
}
}
catch {
print(error)
}
推荐阅读
- javascript - Lambda 无服务器如何从另一个函数返回错误消息?
- java - 将 Jetty 迁移到 SpringBoot Jetty
- c# - 如何使用选项模式在启动时配置依赖项?
- flask - 在烧瓶中使用搜索表单进行分页
- wildfly - 为什么嵌入式 vaadin 14 组件不出现在 XHTML 页面上?
- amazon-s3 - S3 批量操作:通过批量操作 ui 创建对象标记失败
- java-native-interface - 如何编译 Swig 示例?
- python - 使用 to_csv 方法转换 DataFrame 后,我在计算机上找不到它
- java - 为什么我可以透过透明面看到不可见的网格面?
- javascript - 我想将我的所有表从我的数据库显示到 API