iOS 将数据写入文件,文件不存在
iOS Write Data to file, FILE DOES NOT EXIST
我正在尝试在 cacheDirectory 中写入图像的数据,如下所示:
let imageData = UIImageJPEGRepresentation(image, 1.0) else { fatalError("Impossible to read the image") }
try! imageData.write(to: cachedImageURL, options: .atomic)
print(fileManager.fileExists(atPath: cachedImageURL.absoluteString))
其中 image 是工作的 UIImage。
Print 语句总是 returns False。该文件永远不会被写入,并且由于“try!”
引发任何异常
有什么想法吗?
打印缓存的ImageURL,看起来像这样
file:///var/mobile/Containers/Data/Application/7B6B72C8-E794-4474-A658-48B66AEA31EC/Library/Caches/79d0e60e-5961-4538-bd9f-28187f4e26d0.jpg
您可以尝试使用以下代码将图像保存到缓存目录
*注意:如果您要保存多张图片,请为所有图片提供不同的名称
let fileManager = FileManager.default
let imageName = "image.jpg" //Need to change if more images want to save
do {
let cachesDirectory = try fileManager.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let fileURL = cachesDirectory.appendingPathComponent(imageName)
let image = your image //Give your image here
if let imageData = UIImageJPEGRepresentation(image, 1.0) {
try imageData.write(to: fileURL)
print("Image Saved")
}
} catch {
print(error.localizedDescription)
}
刚弄明白。问题来自我的 print
print(fileManager.fileExists(atPath: cachedImageURL.absoluteString))
应该是cachedImageURL.path而不是cachedImageURL.absoluteString
print(fileManager.fileExists(atPath: cachedImageURL.path))
我正在尝试在 cacheDirectory 中写入图像的数据,如下所示:
let imageData = UIImageJPEGRepresentation(image, 1.0) else { fatalError("Impossible to read the image") }
try! imageData.write(to: cachedImageURL, options: .atomic)
print(fileManager.fileExists(atPath: cachedImageURL.absoluteString))
其中 image 是工作的 UIImage。 Print 语句总是 returns False。该文件永远不会被写入,并且由于“try!”
引发任何异常有什么想法吗?
打印缓存的ImageURL,看起来像这样
file:///var/mobile/Containers/Data/Application/7B6B72C8-E794-4474-A658-48B66AEA31EC/Library/Caches/79d0e60e-5961-4538-bd9f-28187f4e26d0.jpg
您可以尝试使用以下代码将图像保存到缓存目录
*注意:如果您要保存多张图片,请为所有图片提供不同的名称
let fileManager = FileManager.default
let imageName = "image.jpg" //Need to change if more images want to save
do {
let cachesDirectory = try fileManager.url(for: .cachesDirectory, in: .userDomainMask, appropriateFor:nil, create:false)
let fileURL = cachesDirectory.appendingPathComponent(imageName)
let image = your image //Give your image here
if let imageData = UIImageJPEGRepresentation(image, 1.0) {
try imageData.write(to: fileURL)
print("Image Saved")
}
} catch {
print(error.localizedDescription)
}
刚弄明白。问题来自我的 print
print(fileManager.fileExists(atPath: cachedImageURL.absoluteString))
应该是cachedImageURL.path而不是cachedImageURL.absoluteString
print(fileManager.fileExists(atPath: cachedImageURL.path))