0

I am trying to save to the documents directory in iOS, taking largely from these questions: Save An Image To Application Documents Folder From UIView On IOS and how to save video in documents folder then upload to server

Here is my problem. The following code does NOT work to save:

NSString *mov = @".mov";
NSString *finalPath = [NSString stringWithFormat: @"/%@%@", self.videoChallengeID, mov];
NSString *videoPath= [[NSString alloc] initWithString:[NSString stringWithFormat:finalPath,documentsDirectory]];

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:videoPath forKey:self.videoChallengeID];
BOOL success = [self.videoData writeToFile:videoPath atomically:NO];

But the following code DOES work to save:

NSString *videoPath= [[NSString alloc] initWithString:[NSString stringWithFormat:@"%@/thisWorks.mov",documentsDirectory]];

NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
[defaults setObject:videoPath forKey:self.videoChallengeID];
BOOL success = [self.videoData writeToFile:videoPath atomically:NO];

The only difference is that the path I am writing to in the example where it does save, it is hard-coded to %@/thisWorks.mov whereas with the other example, the path is the result of 2 concatenated strings.

But I need the path I save to to vary, not be hard coded. How can I fix this?

Community
  • 1
  • 1
jjjjjjjj
  • 4,203
  • 11
  • 53
  • 72

2 Answers2

0

Have you debugged your videoPath from your first example? Judging by the code it looks like you are building the path backwards by adding the finalPath then the documents directory try doing it like this:

NSString *videoPath = [documentsDirectory stringByAppendingString:finalPath];
zfetters
  • 447
  • 2
  • 11
-1

What you are looking at is something like this:

NSString *documentsDirectory = @"A_Directory/Documents";
NSString *fileName           = @"SomeVideoName";
NSString *fileType           = @".mov";

You need to combine all of these to make:

@"A_Directory/Documents/SomeVideoName.mov"

You can get that using:

NSString *fullPath = [NSString StringWithFormat:@"%@/%@%@", documentsDirectory, fileName fileType];

Or you can utilize NSStrings path methods

stringByAppendingPathComponent
stringByAppendingPathExtension

if you change

NSString *fileType = @".mov";

To

NSString *fileType = @"mov";

You do this:

NSString *pathWithOutExtension = [documentsDirectory stringByAppendingPathComponent:fileName];
NSString *fullPath = [pathWithOutExtension stringByAppendingPathExtension:fileType];
Jaybit
  • 1,864
  • 1
  • 13
  • 20
  • thanks for the response. Neither of those worked for me though, both just added a slash before the .mov part of the string. so my finalPath was xxxx/.mov (xxxx being the videoChallengeID) for both cases – jjjjjjjj Mar 29 '16 at 20:44