ios - 为什么我保存在目录中的图像在安装新版本后不显示?

标签 ios swift swift3 xcode8

我这样从用户的照片库中保存图像

func saveImage (image: UIImage, path: String ) -> Bool{
    let jpgImageData = UIImageJPEGRepresentation(image, 1.0)
    let result = jpgImageData!.writeToFile(path, atomically: true) 
    return result
}

func getDocumentsURL() -> NSURL {
    let documentsURL = NSFileManager.defaultManager().URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
    return documentsURL
}

func fileInDocumentsDirectory(filename: String) -> String 
    let fileURL = getDocumentsURL().URLByAppendingPathComponent(filename)
    return fileURL.path!
}

let imagePath = fileInDocumentsDirectory(myImageName)
saveImage(yourPickedImage, path: imagePath)

我是这样读那些图片的

func loadImageFromPath(path: String) -> UIImage? {
    let image = UIImage(contentsOfFile: path)
    return image
}

func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {

    let cell = collectionView.dequeueReusableCell(withReuseIdentifier: reuseIdentifier, for: indexPath) as! Cell


    cell.backgroundImage.image = loadImageFromPath(String(Globals.imagesArray[(indexPath as NSIndexPath).item]))

一切正常,直到我在 Xcode 8 中安装新版本,图像才加载到 UIImageView 中。

我感觉可能是文件路径发生了变化,因为如果我退出并重新启动应用程序,图像确实会加载,但不是从新构建的。

我该如何补救?

谢谢

最佳答案

正如您已经怀疑的那样,问题在于您正在保存 path 的值并稍后使用它来尝试加载文件。你不能那样做,因为每次的路径都不一样。您需要完成调用 imagePath = fileInDocumentsDirectory(myImageName) 的所有工作才能加载路径,就像您保存 它。

(此外,虽然这与您的问题无关,但构造一个 URL 然后从中创建一个字符串路径,就像您在 fileInDocumentsDirectory 中所做的那样,是愚蠢的。始终坚持使用 URL !)

关于ios - 为什么我保存在目录中的图像在安装新版本后不显示?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39551586/

相关文章:

ios - 删除弹出 View Controller -swift

ios - 实例成员无法使用

iOS模拟器不向运行tomcat webservice的localhost mac发送http请求

ios - ios 中的 UIActivityViewController 与 UIDocumentInteractionController

ios - 如何添加样式?

ios - 如何创建 UILabel 动态高度和布局 anchor 约束?

ios - 从内存中删除未使用的 ViewController

ios - Swift - 在锁屏/控制中心隐藏 URL

ios - 当父 UIViewController 调整容器 View 的大小时, subview Controller 不会自动布局

ios - 两个 ImageView 添加到我使用对象库添加的 ScrollView 中?