Swift中使用Data导入UInt16二进制文件运行时失败求助
Swift读取本地二进制文件时出现NSURLConnection错误码-1002
问题背景
学习Swift开发时,编写了一个处理UInt16二进制文件的类,用于生成并显示CGImage灰度图像。此前功能正常,整理代码后突然出现Data(contentsOf:)读取文件的运行时错误,文件无法加载。
已完成的排查:
- 字符串路径与生成的URL对比,仅空格被转义为
%20 - 调试确认文件存在且具备可读权限
- 应用未启用沙箱,读取权限配置正常(曾损坏授权文件,已新建应用并复制代码)
- Xcode、Swift及macOS均为最新版本
调试信息
路径数据
imagePath = (String) "/Users/nate/2023 02 22 1330 SwiftDecomTestData/rawPlus/DN/IR3_2017-12-08_018_029_dn.raw" fileURL Foundation.URL? "/Users/nate/2023%2002%2022%201330%20SwiftDecomTestData/rawPlus/DN/IR3_2017-12-08_018_029_dn.raw"
错误代码片段
private func importAndScaleImageData() { // Start DEBUG verification let filePath = self.imagePath // data file if checkIfFileExists(atPath: filePath) { print("file exists!") if !checkFileReadability(filePath: filePath) { print("Unable to read the file.") print("imagePath \(filePath)") fatalError() } } else { print("file does not exist!") fatalError() } // No runtime errors above ######### // END DEBUG verification do { // NOTE input file path as String was cast as URL let data8 = try Data(contentsOf: self.fileURL!) // ERROR self.backingImage = data8.uint16Array() // not reached } catch { // error caught here ####### print("importAndScaleImageData: URL \(self.fileURL!) \(error)") fatalError("Error found importing \(self.fileURL!.absoluteString)") } // remainder of the method skipped }
错误提示
NSURLConnection finished with error - code -1002
中文翻译:不支持的URL方案
解决方案
问题根源在于本地文件URL的创建方式错误:直接将字符串路径转换为URL时,系统会将其当作网络URL处理,而非本地文件路径,导致出现“不支持的URL方案”错误。
修复步骤
- 使用
URL(fileURLWithPath:)方法生成正确的本地文件URL,该方法会自动处理路径中的空格、特殊字符,添加file://前缀。 - 避免强制解包
fileURL,改用可选绑定提升代码安全性。
修改后的代码
private func importAndScaleImageData() { // DEBUG验证逻辑优化 let filePath = self.imagePath guard checkIfFileExists(atPath: filePath), checkFileReadability(filePath: filePath) else { print("文件不存在或不可读: \(filePath)") fatalError() } do { // 正确创建本地文件URL let fileURL = URL(fileURLWithPath: filePath) let data8 = try Data(contentsOf: fileURL) self.backingImage = data8.uint16Array() } catch { print("importAndScaleImageData: 读取错误 \(error)") fatalError("导入文件失败: \(filePath)") } }
原理说明
URL(fileURLWithPath:)是专门用于生成本地文件系统URL的API,它会自动处理路径中的转义字符、添加正确的file://协议前缀,确保Data(contentsOf:)能够识别为本地文件读取操作,而非网络请求,从而解决错误码-1002的问题。
内容的提问来源于stack exchange,提问作者Nate Lockwood
相关产品推荐
相关产品推荐

