保存到iOS

时间:2016-03-29 20:16:35

标签: ios nsstring

我正在尝试保存到iOS中的文档目录,主要来自以下问题: Save An Image To Application Documents Folder From UIView On IOShow to save video in documents folder then upload to server

这是我的问题。以下代码无法保存:

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

但是以下代码可以保存:

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

唯一的区别是我在其保存的示例中写入的路径,它被硬编码为%@ / thisWorks.mov而对于另一个示例,路径是2个连接字符串的结果。

但我需要保存的路径可以改变,而不是硬编码。我该如何解决这个问题?

2 个答案:

答案 0 :(得分:0)

您是否从第一个示例调试了videoPath?从代码看,看起来你正在通过添加finalPath向后构建路径,然后文档目录尝试这样做:

ADDR                                   NUM1                NUM2

-------------------------------------- ------------------- ------------------
ILLD/ELKJS/00000000/ELKJS/FHSH
ILLD/EFECTE/0116988-7-002/ADFA/ADFG
IIODK/1573230-0/2216755-7/             1573230-0           2216755-7
IIODK/1573230-0/2216755-700/WRITE      1573230-0
IIODK/TEST/1573230-0/2216755-700/WRITE 1573230-0           
1234567-8                              1234567-8
1234567-8/9876543-2                    1234567-8           9876543-2
1234567-8/TEST/9876543-2               1234567-8           9876543-2

答案 1 :(得分:-1)

你在看什么是这样的:

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

您需要将所有这些结合起来:

@"A_Directory/Documents/SomeVideoName.mov"

你可以使用:

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

或者您可以使用NSStrings路径方法

stringByAppendingPathComponent
stringByAppendingPathExtension

如果你改变了

NSString *fileType = @".mov";

NSString *fileType = @"mov";

你这样做:

NSString *pathWithOutExtension = [documentsDirectory stringByAppendingPathComponent:fileName];
NSString *fullPath = [pathWithOutExtension stringByAppendingPathExtension:fileType];