ios - 无法将类型 'String?' 的值转换为预期的参数类型 'URL'

标签 ios swift3

我正在尝试从主包中的文件加载数据。当我使用这段代码时

 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/

相关文章:

ios - 从 firebase 检索到 swift 3 中的多个按钮

ios - X代码 : Multiple Target

ios - 是否可以在表格 View 的部分标题中将文本左右对齐?

ios - 从 UIColor 中提取 RGB 值

swift - 向网络服务器发送参数

ios - 行的 CoreData 更新导致空行的插入

ios - Objective-C - 同时关闭表单和页面表

ios - 如何通过 Switch on 状态显示 UIImageView?那么......我如何向 UIImageView 添加约束以使其居中或类似?

ios - 如何在 CallKit 中结束通话

ios - Segue 没有被转入(swift 3)