ios 删除 iPhone 沙箱(文档文件夹)中的所有文件?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4793278/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-30 18:39:45  来源:igfitidea点击:

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

iphoneiosios4

提问by Jinah Adam

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

有没有一种简单的方法可以删除我保存在应用程序文档文件夹中的所有文件(图像)?

回答by Ole Begemann

NSFileManager *fileMgr = [[[NSFileManager alloc] init] autorelease];
NSError *error = nil;
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
if (error == nil) {
    for (NSString *path in directoryContents) {
        NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
        BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
        if (!removeSuccess) {
            // Error handling
            ...
        }
    }
} else {
    // Error handling
    ...
}

回答by Tiberiu Oprea

For Swift devs:

对于 Swift 开发者:

let fileMgr = NSFileManager()
let dirPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)[0]
if let directoryContents = try? fileMgr.contentsOfDirectoryAtPath(dirPath)
{
    for path in directoryContents 
    {   
        let fullPath = (dirPath as NSString).stringByAppendingPathComponent(path)
        do 
        {
            try fileMgr.removeItem(atPath: fullPath)
            print("Files deleted")
        } 
        catch let error as NSError 
        {
            print("Error deleting: \(error.localizedDescription)")
        }
    }
}

回答by Msmit1993

Code did not work with IOS 7 and Xcode 5 so edited to work with my app. Big credits to @Ole Begemann and @pablasso.

代码不适用于 IOS 7 和 Xcode 5,因此进行了编辑以适用于我的应用程序。感谢@Ole Begemann 和@pablasso。

-(void)EmptySandbox
{
    NSFileManager *fileMgr = [[NSFileManager alloc] init];
    NSError *error = nil;
    NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    NSString *documentsDirectory = [paths objectAtIndex:0];
    NSArray *files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];

    while (files.count > 0) {
        NSString *documentsDirectory = [paths objectAtIndex:0];
        NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
        if (error == nil) {
            for (NSString *path in directoryContents) {
                NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
                BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
                files = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:nil];
                if (!removeSuccess) {
                    // Error
                }
            }
        } else {
            // Error
        }
    }
}

回答by Luong Huy Duc

- (void)removeFile
{
    // you need to write a function to get to that directory
    NSString *filePath = [self getDirectory];
    NSFileManager *fileManager = [NSFileManager defaultManager];  
    if ([fileManager fileExistsAtPath:filePath]) 
    {
        NSError *error;
        if (![fileManager removeItemAtPath:filePath error:&error])
        {
            NSLog(@"Error removing file: %@", error); 
        };
    }
}

I believe this is shorter.

我相信这是更短的。

回答by Sam

Swift 2.1 with some extra's:

Swift 2.1 有一些额外的:

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)
}

回答by mahesh chowdary

 NSFileManager *fileMgr = [[[NSFileManager alloc] init] autorelease];
NSError *error = nil;
NSArray *directoryContents = [fileMgr contentsOfDirectoryAtPath:documentsDirectory error:&error];
 if (error == nil) {
   for (NSString *path in directoryContents) {
    NSString *fullPath = [documentsDirectory stringByAppendingPathComponent:path];
    BOOL removeSuccess = [fileMgr removeItemAtPath:fullPath error:&error];
    if (!removeSuccess) {
        // Error handling
        ...
    }
}
} else {
 // Error handling
...
}

回答by AXE

It may not be applicable in all cases but generally it would be more efficient to put all the files in a custom directory inside Documents Directory and then use removeItemAtPath:error:to delete that directory and create it again. E.g.:

它可能并不适用于所有情况,但通常将所有文件放在 Documents Directory 内的自定义目录中,然后removeItemAtPath:error:删除该目录并再次创建它会更有效。例如:

// Clear cache
NSError *error;
[[NSFileManager defaultManager] removeItemAtPath:cacheDirectory error:&error];
if (error)
{
    // error handling
}

// Create cache directory again
NSError *error2;
[[NSFileManager defaultManager] createDirectoryAtPath:cacheDirectory withIntermediateDirectories:YES attributes:nil error:&error2];
if (error2)
{
    // error handling
}