NSFileManager delete contents of directory

后端 未结 9 1740
你的背包
你的背包 2021-01-30 17:13

How do you delete all the contents of a directory without deleting the directory itself? I want to basically empty a folder yet leave it (and the permissions) intact.

9条回答
  •  难免孤独
    2021-01-30 17:43

    Swift 2.1.1:

    public func deleteContentsOfFolder()
    {
        // folderURL
        if let folderURL = self.URL()
        {
            // enumerator
            if let enumerator = NSFileManager.defaultManager().enumeratorAtURL(folderURL, includingPropertiesForKeys: nil, options: [], errorHandler: nil)
            {
                // item
                while let item = enumerator.nextObject()
                {
                    // itemURL
                    if let itemURL = item as? NSURL
                    {
                        do
                        {
                            try NSFileManager.defaultManager().removeItemAtURL(itemURL)
                        }
                        catch let error as NSError
                        {
                            print("JBSFile Exception: Could not delete item within folder.  \(error)")
                        }
                        catch
                        {
                            print("JBSFile Exception: Could not delete item within folder.")
                        }
                    }
                }
            }
        }
    }
    

提交回复
热议问题