使用路径从本地URL文件加载图像

时间:2018-05-23 19:23:40

标签: ios swift uiimage

在我的应用程序中,我正在将图像写入URL文件并保存相关URL以便稍后检索图像。这就是我正在做的事情,但它不起作用。你有什么不对的吗?

let imageRelativeURL = pendingPostData[2]
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let urlString = "\(documentsPath)/\(imageRelativeURL).jpg"
let image = UIImage(contentsOfFile: urlString)
// This is the line that is causing the error
let imageData = UIImageJPEGRepresentation(image!, 1.0)

我收到此错误:

  

线程1:致命错误:包装可选值时意外发现nil

这就是我保存相对URL的方式。

let uniqueRelativeID = NSUUID().uuidString
let documentsPath = NSSearchPathForDirectoriesInDomains(.documentDirectory, .userDomainMask, true)[0] as NSString
let outputPath = "\(documentsPath)/\(uniqueRelativeID).jpg"
let relativePath = "\(uniqueRelativeID).jpg"
let relativeURL = URL(fileURLWithPath: relativePath)
let imageURL = URL(fileURLWithPath: outputPath, relativeTo: relativeURL)

do {
    try UIImageJPEGRepresentation(chosenImg, 1.0)?.write(to: imageURL)
} catch {
    print("There was a problem writing image file.")
}

saveVideoData(data: imageURL.relativeString)

0 个答案:

没有答案