【发布时间】:2015-01-12 15:48:57
【问题描述】:
是否可以在NSDocumentDirectory 的自定义文件夹中保存文件(任何类型)?我的意思是每次我尝试保存时都将其用作资源文件路径:
NSArray *pathComponents = [NSArray arrayWithObjects:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], fileName, nil];
outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
或
NSString *imageDirectory = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0];
因此它总是保存在以下目录中,~/Library/Application Support/iPhone Simulator/......./Documents/file.ext
但是是否可以将该文件保存在这样的自定义文件夹中:~/Library/Application Support/iPhone Simulator/......./Documents/CustomFolder/file.ext。
如果是,您能告诉我有关过程的详细信息吗?
提前致谢。
祝你有美好的一天。
补充:
这里,其实我保存了一个音频录音文件。该文件的名称来自当前时间。我想将该录音文件保存在自定义文件夹中。
这是我的代码:
- (NSString *) dateString
{
// return a formatted string for a file name
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
formatter.dateFormat = @"ddMMMYYY_hh:mm:ssa";
return [[formatter stringFromDate:[NSDate date]] stringByAppendingString:@".m4a"];
}
// Set the audio file
NSArray *pathComponents = [NSArray arrayWithObjects:[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject], fileName, nil];
outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
在outputFileURL我保存我录制的声音。
我试试这个:
// Set the audio file
NSString *customDirectoryPath = [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject];
customDirectoryPath = [customDirectoryPath stringByAppendingPathComponent:@"MyCustomDirectory"];
NSArray *pathComponents = [NSArray arrayWithObjects:customDirectoryPath, fileName, nil];
NSLog(@"pathComponents %@", pathComponents);
outputFileURL = [NSURL fileURLWithPathComponents:pathComponents];
NSLog(@"outputFileURL %@", outputFileURL);
文件夹创建没有任何问题,但音频文件未保存在该文件夹中。 谢谢。
【问题讨论】:
-
在控制台上打印时的 outputFileURL 是什么?检查它是否是正确的文件路径
-
@Puran
NSLog显示有一个新创建的文件夹。但实际上它并没有被创造出来。因为stringByAppendingPathComponent不见了,NSString *filePath = [folderPath stringByAppendingPathComponent:fileName];是Rameswar先生提供的神奇台词。多谢兄弟。 :)
标签: ios objective-c nsurl nsdocumentdirectory