ios 如何在Swift中访问应用程序包中包含的文件?

6qqygrtg  于 2022-12-30  发布在  iOS
关注(0)|答案(8)|浏览(147)

我知道有一些问题与此相关,但它们是在Objective-C中。
如何在实际的iPhone上使用Swift访问应用中包含的.txt文件?我希望能够读取和写入该文件。Here是我的项目文件,如果您想查看的话。如有必要,我很乐意添加详细信息。

3lxsmp7m

3lxsmp7m1#

只需在应用程序包中搜索资源

var filePath = NSBundle.mainBundle().URLForResource("file", withExtension: "txt")

但是,您无法写入它,因为它位于应用程序资源目录中,您必须在文档目录中创建它才能写入它

var documentsDirectory: NSURL?
var fileURL: NSURL?

documentsDirectory = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask).last!
fileURL = documentsDirectory!.URLByAppendingPathComponent("file.txt")

if (fileURL!.checkResourceIsReachableAndReturnError(nil)) {
    print("file exist")
}else{
    print("file doesnt exist")
    NSData().writeToURL(fileURL!,atomically:true)
}

现在您可以从fileURL访问它

编辑-2018年8月28日

以下是在Swift 4.2中执行此操作的方法

var filePath = Bundle.main.url(forResource: "file", withExtension: "txt")

在文档目录中创建它

if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
   let fileURL = documentsDirectory.appendingPathComponent("file.txt")
   do {
       if try fileURL.checkResourceIsReachable() {
           print("file exist")
       } else {
           print("file doesnt exist")
           do {
            try Data().write(to: fileURL)
           } catch {
               print("an error happened while creating the file")
           }
       }
   } catch {
       print("an error happened while checking for the file")
   }
}
lskq00tm

lskq00tm2#

Swift 3,基于Karim’s answer
阅读

您可以通过捆绑包的资源读取应用捆绑包中包含的文件:

let fileURL = Bundle.main.url(forResource:"filename", withExtension: "txt")

"写作"
但是,您不能在那里写入。您需要创建一个副本,最好在Documents目录中:

func makeWritableCopy(named destFileName: String, ofResourceFile originalFileName: String) throws -> URL {
    // Get Documents directory in app bundle
    guard let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last else {
        fatalError("No document directory found in application bundle.")
    }

    // Get URL for dest file (in Documents directory)
    let writableFileURL = documentsDirectory.appendingPathComponent(destFileName)

    // If dest file doesn’t exist yet
    if (try? writableFileURL.checkResourceIsReachable()) == nil {
        // Get original (unwritable) file’s URL
        guard let originalFileURL = Bundle.main.url(forResource: originalFileName, withExtension: nil) else {
            fatalError("Cannot find original file “\(originalFileName)” in application bundle’s resources.")
        }

        // Get original file’s contents
        let originalContents = try Data(contentsOf: originalFileURL)

        // Write original file’s contents to dest file
        try originalContents.write(to: writableFileURL, options: .atomic)
        print("Made a writable copy of file “\(originalFileName)” in “\(documentsDirectory)\\\(destFileName)”.")

    } else { // Dest file already exists
        // Print dest file contents
        let contents = try String(contentsOf: writableFileURL, encoding: String.Encoding.utf8)
        print("File “\(destFileName)” already exists in “\(documentsDirectory)”.\nContents:\n\(contents)")
    }

    // Return dest file URL
    return writableFileURL
}

示例用法:

let stuffFileURL = try makeWritableCopy(named: "Stuff.txt", ofResourceFile: "Stuff.txt")
try "New contents".write(to: stuffFileURL, atomically: true, encoding: String.Encoding.utf8)
wdebmtf2

wdebmtf23#

只是一个快速更新使用此代码与Swift 4:

Bundle.main.url(forResource:"YourFile", withExtension: "FileExtension")

以下内容已更新,以说明如何写出文件:

var myData: Data!

func checkFile() {
    if let documentsDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).last {
        let fileURL = documentsDirectory.appendingPathComponent("YourFile.extension")
        do {
            let fileExists = try fileURL.checkResourceIsReachable()
            if fileExists {
                print("File exists")
            } else {
                print("File does not exist, create it")
                writeFile(fileURL: fileURL)
            }
        } catch {
            print(error.localizedDescription)
        }
    }
}

func writeFile(fileURL: URL) {
    do {
        try myData.write(to: fileURL)
    } catch {
        print(error.localizedDescription)
    }
}

这个特殊的例子不是最灵活的,但是通过一些工作,您可以轻松地传入您自己的文件名、扩展名和数据值。

esbemjvw

esbemjvw4#

🎁属性 Package -提取并转换为正确的数据类型

这个简单的 Package 器可以帮助您以最干净的方式从任何包中加载任何文件:

@propertyWrapper struct BundleFile<DataType> {
    let name: String
    let type: String
    let fileManager: FileManager = .default
    let bundle: Bundle = .main
    let decoder: (Data) -> DataType

    var wrappedValue: DataType {
        guard let path = bundle.path(forResource: name, ofType: type) else { fatalError("Resource not found: \(name).\(type)") }
        guard let data = fileManager.contents(atPath: path) else { fatalError("Can not load file at: \(path)") }
        return decoder(data)
    }
}

用法:

@BundleFile(name: "avatar", type: "jpg", decoder: { UIImage(data: $0)! } )
var avatar: UIImage

您可以根据需要定义任何解码器

nfeuvbwi

nfeuvbwi5#

Swift 5.1中从包中获取文件

//For Video File
let stringPath = Bundle.main.path(forResource: "(Your video file name)", ofType: "mov")

let urlVideo = Bundle.main.url(forResource: "Your video file name", withExtension: "mov")
jucafojl

jucafojl6#

包是只读的。您可以使用NSBundle.mainBundle().pathForResource以只读方式访问文件,但要进行读写访问,您需要将文档复制到Documents文件夹或tmp文件夹。

6ju8rftf

6ju8rftf7#

捆绑包可以写入。您可以使用Bundle.main.path将文件添加到Copy Bundles Resource中以覆盖文件。

ffscu2ro

ffscu2ro8#

我不得不使用另一个包中的文件。所以,下面的代码对我很有用。当你使用框架时,这是必需的。

let bundle = Bundle(for: ViewController.self)
let fileName = bundle.path(forResource: "fileName", ofType: "json")

相关问题