Swift实用:从Bundle读取文件内容

当你建立了一个Swift项目,需要将一些固定的文本,比如html源码等,可以内置了一个文件temp.html,直接拖入项目中:

2025746-5144def991e15994.png

这个文件在打包的时候会被打包到Bunlde文件中,当你需要读取里面的内容时,可以用String的初始化方法contentsOfFile,具体代码如下:

if let filepath = Bundle.main.path(forResource: "temp", ofType: "html") {
    do {
        let contents = try String(contentsOfFile: filepath)
        print(contents)
    } catch {
        // 内容无法加载
    }
} else {
    // 文件未找到
}

猜你喜欢

转载自blog.csdn.net/weixin_33859665/article/details/86931929