简体   繁体   中英

saving to documents directory in iOS

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?

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];

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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM