Cannot convert value of type 'String?' to expected argument type 'URL'

佐手、 提交于 2020-01-14 14:25:30

问题


I'm trying to load data from file which was in main bundle. When I use this code

 let path = Bundle.main.path(forResource: "abc", ofType: "txt")
 let dataTwo = try! Data(contentsOf: path)\\ error here

Also I tried to convert String to URL

 let dataTwo = try! Data(contentsOf: URL(string: "file://\(path)")!)

But after execution am getting this

fatal error: unexpectedly found nil while unwrapping an Optional value


回答1:


You may want to use .url instead:

let url = Bundle.main.url(forResource: "abc", withExtension:"txt")
let dataTwo = try! Data(contentsOf: url!)

and safely handle errors instead of force unwrapping.

Simple version:

if let url = Bundle.main.url(forResource: "abc", withExtension:"txt"),
    let dataTwo = try? Data(contentsOf: url) 
{
    // use dataTwo
} else {
    // some error happened
}

Even better:

do {
    guard let url = Bundle.main.url(forResource: "abc", withExtension:"txt") else {
        return
    }
    let dataTwo = try Data(contentsOf: url)
    // use dataTwo
} catch {
    print(error)
}

This way you don't need to convert a path to an URL, because you're using an URL from the beginning, and you can handle errors. In your specific case, you will know if your asset is there and if your URL is correct.




回答2:


For file URL use init(fileURLWithPath:) constructor.

Also here

let dataTwo = try! Data(contentsOf: path)\\ error here

get rid of try! and use proper error handling to see whats the real error happens.



来源:https://stackoverflow.com/questions/40360716/cannot-convert-value-of-type-string-to-expected-argument-type-url

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!