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

时间:2019-01-11 17:31:06

标签: swift uicollectionview nsdocumentdirectory

这是此SO帖子:How to rename files in documents directory中解决的相同问题,但对我没有任何帮助。这是我遇到的唯一一篇与我的问题有关的其他帖子。

我有一个收集视图,其中通过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)
}

1 个答案:

答案 0 :(得分:0)

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

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)。您应该能够按顺序重命名每个文件,以数字顺序无间断地恢复它们,因为上述方法并不关心旧文件的索引。

对于图像阵列,您应该能够使用要创建的新文件路径创建一个新阵列,替换旧阵列,然后触发重新加载。这样,您也不必从图像阵列中删除删除项,而是在重建对象时将其删除。

让我知道这是否足以让您入门,否则,我可以尝试整理一个完整的示例。