我需要将所有音频和视频网址保存到来自服务器的文档目录中。我试过一个示例代码
NSData *urlData = [NSData dataWithContentsOfURL:[NSURL URLWithString: "http://www.ebookfrenzy.com/ios_book/movie/movie.mp4"]];
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath_ = [documentsDirectory stringByAppendingPathComponent:@"/MyFolder"];
NSString *newStr = [@"test" stringByAppendingString:[NSString stringWithFormat:@".mp4"]];
NSString *FilePath = [NSString stringWithFormat:@"%@/%@",dataPath_,newStr];
[urlData writeToFile:FilePath atomically:YES];
该文件夹正在文档目录中创建,但视频未保存到文件夹中。任何人都可以帮助对其进行排序。
答案 0 :(得分:1)
您应该正确构建路径,并且应该进行一些基本的错误检查:
NSData *urlData = [NSData dataWithContentsOfURL:[NSURL URLWithString: @"http://www.ebookfrenzy.com/ios_book/movie/movie.mp4"]];
if (urlData) {
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *dataPath = [documentsDirectory stringByAppendingPathComponent:@"MyFolder"];
// Create folder if needed
[[NSFileManager defaultFileManager] createDirectoryAtPath:dataPath withIntermediateDirectories:YES attributes:nil error:nil];
NSString *filePath = [dataPath stringByAppendingPathComponent:@"test.mp4"];
if ([urlData writeToFile:filePath atomically:YES]) {
// yeah - file written
} else {
// oops - file not written
}
} else {
// oops - couldn't get data
}