带有URL的writeToFile - 下一个会话不存在URL

时间:2012-08-28 04:44:24

标签: iphone objective-c ios xcode

我正在使用writeToFile将音频文件写入本地iphone目录。下次启动应用程序时,路径/ URL不再存在,我无法检索我的文件。

非常感谢任何帮助。

保存:

    NSArray *dirPaths;
    NSString *docsDir; 
    dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = [dirPaths objectAtIndex:0];
    NSString *tempFileName = [[NSString alloc] init];
    tempFileName = [[alertView textFieldAtIndex:0]text];
    NSString *soundFilePath = [docsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.wav", tempFileName]];
    BOOL success = [videoData writeToFile:soundFilePath atomically:YES];

读:

if ([[NSFileManager defaultManager] fileExistsAtPath:[urlArray objectAtIndex:indexPath.row]])

其中urlArray包含文件的路径,此If语句为false。

2 个答案:

答案 0 :(得分:1)

为什么不在NSMutableArray中保存filePath,在NSUserDefault中保存

 //After writing file in doc dir
 if(success)
 {
   // Store the data
   NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
   if(![defaults objectForKey:@"filePaths"]) //creating mutable array for first time
   {
      NSMutableArray *arrFilePaths = [NSMutableArray alloc]init];
      [defaults setObject:arrFilePaths forKey:@"filePaths"];
   }
   else //saving new soundFilePath in mutable array
   {
      NSMutableArray *arrFilePaths = [defaults objectForKey:@"filePaths"];
      [arrFilePaths addObject:soundFilePath];
      [defaults setObject:arrFilePaths forKey:@"filePaths"];
      [defaults synchronize];
   }

 }

现在你可以这样读:

if([[defaults objectForKey:@"filePaths"] objectAtIndex:indexPath.row])
{
  if ([[NSFileManager defaultManager] fileExistsAtPath:[[defaults objectForKey:@"filePaths"] objectAtIndex:indexPath.row]])
  {
     //here is your file
  }
}

答案 1 :(得分:0)

每次启动应用程序时,您都需要像在上面那样在NSDocument目录中再次搜索路径。

您可以在AppDelegate类中为filePath创建实例变量didFinishLaunching来记录路径。

dirPaths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
    docsDir = [dirPaths objectAtIndex:0];
    NSString *tempFileName = [[NSString alloc] initWithString:@"PutYourFileName"];
NSString *soundFilePath = [docsDir stringByAppendingPathComponent:[NSString stringWithFormat:@"%@.wav", tempFileName]];