简体   繁体   中英

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

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

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM