如何将目录中的图像追加到数组?

问题描述 投票:0回答:1

我使用此代码将图像附加到目录中的数组中

for myIndex in 1...17 {
                
    let nsDocumentDirectory = FileManager.SearchPathDirectory.documentDirectory
    let nsUserDomainMask = FileManager.SearchPathDomainMask.userDomainMask
    let paths = NSSearchPathForDirectoriesInDomains(nsDocumentDirectory, nsUserDomainMask, true)
    let dirPath = paths.first
    let imageURL = URL(fileURLWithPath: dirPath!).appendingPathComponent("\(index)/\(myIndex).jpg")
    let image = UIImage(contentsOfFile: imageURL.path)
    imageArray.append(image!)
                
}

但是我有这个错误:

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

在这一行中:

imageArray.append(image!)

如何解决?

swift
1个回答
0
投票

这很清楚。在

image
的情况下,您将使用
!
强制展开
nil
。所以,我认为你应该:

  1. 以安全的方式解开图像,例如
    if let
    guard let
if let image = UIImage(contentsOfFile: imageURL.path) {
    imageArray.append(image) //without "!"
}
  1. 仔细检查为什么图像的路径为零。
© www.soinside.com 2019 - 2024. All rights reserved.