2014-12-06 106 views
0

我需要將所有音頻和視頻url保存到來自服務器的文檔目錄中。我已經嘗試了示例代碼ios將音頻和視頻url保存到文檔目錄

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

該文件夾中創建文件目錄,但視頻沒有保存到folder.Can任何人的幫助來排序了這一點。

回答

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 
} 
+0

麥迪,我得到的錯誤在其他部分哎呀,couldn't獲取數據,我有一個NSLog的通過打印urlData檢查它的打印(null)。我如何實現這一目標? – Apple 2014-12-07 04:40:26

+0

我剛剛注意到你在URL字符串之前缺少'@'符號。 – rmaddy 2014-12-07 05:15:34

+0

Maddy,我用@符號但urlData打印爲(null)。 – Apple 2014-12-08 04:45:55

相關問題