Karthikeyan Bose
Karthikeyan Bose

Reputation: 1274

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

Upvotes: 4

Views: 13792

Answers (2)

Eric Aya
Eric Aya

Reputation: 70097

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.

Upvotes: 5

user28434'mstep
user28434'mstep

Reputation: 6600

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.

Upvotes: 0

Related Questions