ios下获得文件的路径

获取本地工程里的资源文件的路径

例如获得文件myfile.txt的路径

NSString *path = [[NSBundle mainBundle] pathForResource:@"myfile" ofType:@"txt"]

将本地路径转换为NSURL

NSURL* url = [NSURL fileURLWithPath:path];

获取app沙盒内的Documents路径

NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);

NSString *basePath = ([paths count] > 0) ? [paths objectAtIndex:0] : nil;
将所有文件存入数组

NSString *string = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *tempFileList = [[NSArray alloc] initWithArray:[fileManager contentsOfDirectoryAtPath:string error:nil]];

移除所有png文件

NSString *extension = @”png”;
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];

NSArray *contents = [fileManager contentsOfDirectoryAtPath:documentsDirectory error:nil];
NSEnumerator *enumerator = [contents objectEnumerator];
NSString *filename;
while ((filename = [enumerator nextObject])) {
if ([[filename pathExtension] isEqualToString:extension]) {
[fileManager removeItemAtPath:[documentsDirectory stringByAppendingPathComponent:filename] error:nil];
}
}

你可能感兴趣的:(iOS开发问题汇总)