Narry
Narry

Reputation: 13

Error Domain=NSCocoaErrorDomain Code=256

    override func viewDidLoad() {
    super.viewDidLoad()
    let dataURLString: String = Bundle.main.path(forResource: "IMG_0568", ofType: "JPG")!
    let dataURL = URL(string: dataURLString)
    do {
        let binaryData = try Data(contentsOf: dataURL!, options: [])
        let kbData = binaryData.subdata(in: 0..<1024)
        let stringArray = kbData.map{String(format: "%02X", $0)}
        let binaryString = stringArray.joined(separator: "-")
        print(binaryString)
        editorTextView.text = (binaryString)
    } catch {
        print("Failed to read the file.")
        //Error Domain=NSCocoaErrorDomain Code=256 "The file “IMG_0568.JPG” couldn’t be opened." UserInfo={NSURL=/Users/..../IMG_0568.JPG}
    }

I want to display the Binary Data of Image File that I have added to my Xcode project (image name: IMG_0568.JPG).

But there's the error

(Error Domain=NSCocoaErrorDomain Code=256 "The file “IMG_0568.JPG” couldn’t be opened." UserInfo={NSURL=/Users/..../IMG_0568.JPG})

How can I fix this problem?

Upvotes: 1

Views: 3386

Answers (1)

vadian
vadian

Reputation: 285039

This is a very common mistake:

URLs in the file system must be initialized with URL(fileURLWithPath

let dataURL = URL(fileURLWithPath: dataURLString)

The difference is:

  • URL(fileURLWithPath expects a path starting with a slash like /Users/myUser/file.ext
  • URL(string expects an URL string including the scheme like file:///Users... or http://example.com

However you can avoid the mistake by using the URL related API of Bundle

let dataURL = Bundle.main.url(forResource: "IMG_0568", withExtension: "JPG")!

Upvotes: 4

Related Questions