我正在尝试从主包中的文件加载数据。当我使用这段代码时
let path = Bundle.main.path(forResource: "abc", ofType: "txt")
let dataTwo = try! Data(contentsOf: path)\\ error here
我还尝试将 String 转换为 URL
let dataTwo = try! Data(contentsOf: URL(string: "file://\(path)")!)
但是执行后我得到了这个
fatal error: unexpectedly found nil while unwrapping an Optional value
最佳答案
您可能想改用 .url
:
let url = Bundle.main.url(forResource: "abc", withExtension:"txt")
let dataTwo = try! Data(contentsOf: url!)
并安全地处理错误而不是强制解包。
简单版:
if let url = Bundle.main.url(forResource: "abc", withExtension:"txt"),
let dataTwo = try? Data(contentsOf: url)
{
// use dataTwo
} else {
// some error happened
}
更好的是:
do {
guard let url = Bundle.main.url(forResource: "abc", withExtension:"txt") else {
return
}
let dataTwo = try Data(contentsOf: url)
// use dataTwo
} catch {
print(error)
}
这样您就不需要将路径转换为 URL,因为您从一开始就使用 URL,并且可以处理错误。在您的特定情况下,您将知道您的 Assets 是否存在以及您的 URL 是否正确。
关于ios - 无法将类型 'String?' 的值转换为预期的参数类型 'URL',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40360716/