Deleting all the files in the iPhone sandbox (documents folder)?

前端 未结 7 2107
清歌不尽
清歌不尽 2020-11-28 05:50

Is there an easy way to delete all the files(images) I saved in the documents folder of the app?

7条回答
  •  小蘑菇
    小蘑菇 (楼主)
    2020-11-28 06:33

    Swift 2.1 with some extra's:

    do {
        let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
        let documentsDirectory = paths[0]
        let documentsDirectoryURL = NSURL(fileURLWithPath: paths[0])
    
        let directoryContents = try NSFileManager.defaultManager().contentsOfDirectoryAtPath(documentsDirectory)
    
        var totalMegaBytes: Double = 0
        var nrOfFiles = 0
    
        for filename in directoryContents {
            let file = documentsDirectoryURL.URLByAppendingPathComponent(filename)
    
    
            let fileAttributes = try NSFileManager.defaultManager().attributesOfItemAtPath(file.path!)
            let fileSize = fileAttributes[NSFileSize] as! Double            
            totalMegaBytes += fileSize/1024/1024
    
            do {
                try NSFileManager.defaultManager().removeItemAtURL(file)
                nrOfFiles++
            }catch let error as NSError{
                print("> Emptying sandbox: could not delete file", filename, error)
            }
        }
    
        print("> Emptying sandbox: Removed \(nrOfFiles) files with a total of \(round(totalMegaBytes))MB")
    
    }catch let error as NSError{
        print("> Emptying sandbox: Error emptying sandbox", error)
    }
    

提交回复
热议问题