文档目录:在 Swift 4.2 中删除文件并重命名剩余文件

Document Directory: delete file and rename remaining files in Swift 4.2

这与 SO post 中解决的问题相同:How to rename files in documents directory 但它对我没有任何帮助。这是我遇到的唯一一个 post 似乎与我的问题有关的问题。

我有一个集合视图,其中图像是通过 didFinishPickingMediaWithInfo 中的 imagePickerController 添加的。它遍历文档目录并根据下一个可用索引号为所选图像命名。因此图像被命名为 image1.jpg、image2.jpg 等。当图像加载到 collectionView 中时,我再次循环并按索引顺序显示图像。当需要删除图像时,我可以在文档目录中找到它并将其删除,但是索引顺序被打断,我无法再加载图像。因此,如果我删除 image3.png,文档目录包含 image1.jpg、image2.jpg、image4.jpg、image5.jpg 等

我当前尝试在目录中重命名或移动图像的代码仍在遍历索引号,当遇到空索引时自然会停止 (image3.jpg)。我怎样才能让 image4.jpg 移动到 image3.jpg 曾经所在的位置(并移动索引后面的所有其他图像,其中图像被删除)?

我无法完全理解重命名文件所需的逻辑。如果您需要更多代码,请告诉我。所有建议表示赞赏。 这是我目前拥有的:

@objc func tapToDelete(recognizer: UITapGestureRecognizer)
{

    let pointInCollectionView = recognizer.location(in: collectionView)
    let indexPath = collectionView.indexPathForItem(at: pointInCollectionView)

    countIndex = (indexPath?.row)! + 1

    let filepath = getFolderAndFilePath() //this gets the folder and filepath of each image


    let alert = UIAlertController(title: "Delete This Image?", message: "Are you sure? This cannot be undone.", preferredStyle: .alert)
    alert.addAction(UIAlertAction(title: "Cancel", style: .cancel, handler: nil))
    alert.addAction(UIAlertAction(title: "Delete", style: .destructive, handler: { (action) in
        do
        {
            try self.fileManager.removeItem(at: filepath as URL)
            self.imageArray.remove(at: self.countIndex)


            self.folderPath = self.getFolderPath()
            if self.folderPath != nil
            {
                var j = 0
                var z = 0
                var finalArray = [String]()

                do
                {
                    let directoryContent = try FileManager.default.contentsOfDirectory(at: self.folderPath! as URL, includingPropertiesForKeys: nil, options: [])


                    for _ in directoryContent
                    {
                        z += 1
                        let fileString = String(format: "image%d.jpg", z)
                        let oldPath = self.folderPath?.appendingPathComponent(fileString)
                        print("filename oldPath : \(String(describing: oldPath))")

                        if self.fileManager.fileExists(atPath: (oldPath?.path)!)
                        {
                            j += 1
                            let newFileName = String(format: "image%d.jpg", j)


                            finalArray.append(newFileName)

                            let newPath = oldPath?.deletingLastPathComponent().appendingPathComponent(newFileName)
                            print("new filename: \(String(describing: newFileName))")

                            _ = try? self.fileManager.moveItem(atPath: (oldPath?.path)!, toPath: (newPath?.path)!)

                        }
                        else
                        {
                            print("no file here")
                            //this is called when we get to the image removed(image3.jpg)
                        }
                        self.collectionView.reloadData() //this reloads the collectionview and updates the count but still shows image3 instead of image4 even though image3 has been removed from the directory
                    }
                }
                catch
                {
                    print("Could not search for urls of files in documents directory: \(error)")
                }
            }
        }
        catch
        {
            print(error)

        }

    }))
    self.present(alert, animated: true)
}

这可能需要一些调整,但是删除文件后的以下方法(伪代码)呢?

let directoryContent = try FileManager.default.contentsOfDirectory(at:   self.folderPath! as URL, includingPropertiesForKeys: nil, options: [])
var index = 1
var newImageArray:[URL] = []
for fileURL in directoryContent
{
    let newFileName = String(format: "image%d.jpg", index)
    let newFilePathURL = makePathAsYouWere()
    _ = try? self.fileManager.moveItem(atPath: fileURL, toPath: newFilePathURL)
    index += 1
    newImageArray.append(newFilePathURL)
}

self.imageArray = newImageArray

collectionView.reload()

基本上,删除文件后,您将拥有一组可以迭代的文件。该列表可能需要排序以使它们按正确的顺序排列,但是一旦它们被排序(file1、file2、file4、file5)。由于上述方法不关心旧文件的索引,因此您应该能够按顺序重命名它们以按数字顺序恢复它们而没有间隙。

对于图像数组,您应该能够使用正在创建的新文件路径创建一个新数组,替换旧数组,然后触发重新加载。有了这个,你也不必从图像数组中删除删除项,它会在你重建东西时被删除。

如果这足以让您入门,请告诉我,否则,我可以尝试整理一个完整的示例。