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}
}
我想显示我已添加到Xcode项目中的图像文件的二进制数据(图像名称:IMG_0568.JPG
)。
但是出现了错误
(错误域= NSCocoaErrorDomain代码= 256&#34;文件“IMG_0568.JPG” 无法打开。&#34;的UserInfo = {NSURL = /用户/..../ IMG_0568.JPG})
如何解决此问题?
答案 0 :(得分:1)
这是一个非常常见的错误:
必须使用URL(fileURLWithPath
let dataURL = URL(fileURLWithPath: dataURLString)
区别在于:
URL(fileURLWithPath
要求路径以/Users/myUser/file.ext
URL(string
需要包含方案的网址字符串,例如file:///Users...
或http://example.com
但是,您可以使用Bundle
let dataURL = Bundle.main.url(forResource: "IMG_0568", withExtension: "JPG")!