ios - 在 Swift 中读/写 JS 文件

标签 ios swift file

尝试在 swift 中读取/写入 js 文件。但有权限错误。 这就是我正在做的事情:

if let path = Bundle.main.path(forResource: "settings", ofType: "js", inDirectory: "config/") {
    do {
        let content = try String(contentsOfFile: path)
        var subContent = content.split(separator: "\r\n")
        subContent[55] = """
        \nuurl: "https://xpto-example/xxx",
        """
        let finalContent = try String(subContent.flatMap({ (subtring) -> String in
            return String(subtring)
        }))
        try finalContent.write(to: URL(fileURLWithPath: path), atomically: false, encoding: .utf8)
    } catch {
        print("content error")
    }
}

实现目标的最佳方式是什么?

我正在尝试将文件从 bundle 复制到 FileManager,文档目录中的此文件是 js 可读的吗?它会以 html 形式加载还是我必须做一些事情?

最佳答案

您必须将写入事件限制在应用程序的 Documents 文件夹中,毫不奇怪,这是 iOS 允许您的应用程序写入权限的唯一位置。

这是一个示例 View Controller ,它将字符串写入磁盘(我刚刚测试成功):

class ViewController: UIViewController {
override func viewDidLoad() {
    super.viewDidLoad()
    let paths = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask)
    let documentsDirectory = paths[0]

    let mydoc = "testdocument"
    let filename = documentsDirectory.appendingPathComponent("output.txt")
    do {
        try mydoc.write(to: filename, atomically: true, encoding: String.Encoding.utf8)
    } catch {
        print("Failed to write!")
        fatalError()
    }
    print("saved!")

}

}

测试成功:

enter image description here

关于ios - 在 Swift 中读/写 JS 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57260864/

相关文章:

ios - 为什么只有第一个任务退出后才调用dispatchGroup.notify?

iphone - NSRepublicOfChinaCalendar 和 NSGregorianCalendar 有什么区别?

ios - 从 'requestImageForAsset' 返回的 UIImage 大小甚至不接近 'targetSize' 设置

ios - Swift 如何在 NSObject 中创建公共(public)变量

java - 网页不显示新文件内容

ios - 将 TICoreDataSync 添加到 ios/mac 项目

ios - 如何在框架(Objective-C)中将类访问器设为私有(private)

swift - 尝试注册一个不是 UICollectionViewCell 子类的单元格类。嗯?

java - 如何通过偏移量读取变化的文本文件

c - 使用 c 从文件中读取特定范围的行