ios 在 Swift 3 中从本地文件加载数据对象

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/42982666/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-31 09:00:27  来源:igfitidea点击:

loading data object from local file in Swift 3

iosswiftswift3

提问by veiko herne

I'm struggling to get an image file loaded in Swift 3. Here is the code:

我正在努力在 Swift 3 中加载图像文件。这是代码:

do {
    let imageData = try Data(contentsOf: imageUrl2.asURL()) 
} catch { 
    print ("loading image file error") 
}

And the current Url String is:

当前的 URL 字符串是:

file:///Users/veikoherne/Library/Developer/CoreSimulator/Devices/889A08D5-B8CC-458C-99FF-643A4BA1A806/data/Containers/Data/Application/F64ED326-7894-4EE7-AA3B-B1BB10DF8259/Documents/img2017-03-23 17:39:24.jpg

and obviously I have checked that this file exists and is valid image. It always ends up telling me "loading image file error". Anyone have experiences loading local data in Swift 3?

显然我已经检查过这个文件是否存在并且是有效的图像。它总是最终告诉我“加载图像文件错误”。任何人都有在 Swift 3 中加载本地数据的经验?

The answer mentioned was using NSData object and probably Swift 2. Current Swift 3 refuses to bridge NSData to Data, that's why I have to use Data.

提到的答案是使用 NSData 对象,可能是 Swift 2。当前的 Swift 3 拒绝将 NSData 桥接到数据,这就是我必须使用数据的原因。

回答by Dharmesh Siddhpura

Loading data from local file you should use "contentsOfFile:" method.

从本地文件加载数据,您应该使用“contentsOfFile:”方法。

Reference link: https://www.hackingwithswift.com/example-code/strings/how-to-load-a-string-from-a-file-in-your-bundle

参考链接:https: //www.hackingwithswift.com/example-code/strings/how-to-load-a-string-from-a-file-in-your-bundle

So in case of reading data you can use:

因此,在读取数据的情况下,您可以使用:

Data(contentsOf: <URL>, options: <Data.ReadingOptions>)

Reading a plain text as a String, use:

将纯文本作为字符串读取,使用:

String(contentsOfFile: <LocalFileDirPath>)

Reading an image from document directory, use:

从文档目录读取图像,使用:

UIImage(contentsOfFile: <LocalFileDirPath>)

Hope this would be helpful!

希望这会有所帮助!

回答by Lexi

I experienced the same issue when trying to retrieve a file that I just downloaded. If you have saved a file from some url like I did, this should work:

我在尝试检索刚刚下载的文件时遇到了同样的问题。如果你像我一样从某个 url 保存了一个文件,这应该可以工作:

let documentDirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first
let localUrl = documentDirectory.appendingPathComponent("somefile.txt")

if FileManager.default.fileExists(atPath: localUrl.path){
    if let cert = NSData(contentsOfFile: localUrl.path) {
        return cert as Data
    }
}