在iOS 9+中,任何尝试从文件中读取的内容都是零。在这种情况下,文件是图像文件路径 使用
NSData(contentsOfFile: stringpath, options: NSDataReadingOptions.DataReadingUncached)
或
NSData(contentsOfFile: stringpath)
操作:
我已从路径中删除了“file://”,现在它有权限问题。
错误域= NSCocoaErrorDomain代码= 257“无法打开文件”IMG_0048.JPG“,因为您无权查看它。” UserInfo = {NSFilePath = / var / mobile / Media / DCIM / 100APPLE / IMG_0048.JPG,NSUnderlyingError = 0x13f978f50 {Error Domain = NSPOSIXErrorDomain Code = 1“不允许操作”}}
我添加了NSAllowArbitraryLoads
并将其设置为true
我试图使用“ NSSearchPathDirectory ”来查找文件但是路径不匹配任何方式
答案 0 :(得分:4)
我遇到了这个错误,因为我试图访问同一个块中的多个文件。对我有用的修复是更改代码结构,以便在尝试获取下一个文件URL之前获取每个文件URL,然后读取。
答案 1 :(得分:1)
您最有可能收到此错误,因为iOS应用只能访问其沙箱中的文件。有关详细信息,请参阅文件系统上的Apple documentation。
答案 2 :(得分:0)
在您的应用程序中,由于沙盒,您无权访问/var/mobile/Media/DCIM/100APPLE/IMG_0048.JPG
的文件。
因此,无论您做什么,都无法使用文件路径初始化NSData
或UIImage
。但您可以使用/var/mobile/Media/DCIM/100APPLE/xxx.mov
访问AVURLAsset
的文件。在我的应用程序中,我通过Photos工具包从图库中提取数据而不是URL,并使用数据初始化UIImage
。
PHImageManager.default().requestImageData(
for: assetObject!, options: options,
resultHandler: {
data, _, _, _ in
if data != nil {
self.assetUrl = movieMaker.createMovieFrom(imageData: data!, duration: Int(CXPreparetValue.imageDuration))
}
})
它对我有用!如果您有其他意见,请告诉我。
答案 3 :(得分:-2)
在我的情况下,文件权限限制太多,所以我无法读取文件。
在访问文件之前为文件添加读写权限解决了它。
do {
// Retrieve any existing attributes
var attrs = try FileManager.default.attributesOfItem(atPath: stringpath)
let existing = (attrs as NSDictionary).filePosixPermissions()
// Set the read+write value in the attributes dict
attrs[.posixPermissions] = existing | 0b110000000
// Update attributes
try FileManager.default.setAttributes(attrs, ofItemAtPath: stringpath)
// Read data from file
let data = try Data(contentsOf: URL(fileURLWithPath: stringpath, isDirectory: false), options: .uncached)
print("success: \(data.count)")
} catch {
print(error)
}
如果您位于具有足够权限的文件夹中,那么即使您之前没有对该文件具有读取权限,也可以更改文件权限。该解决方案应用于https://github.com/ZipArchive/ZipArchive/issues/293。