iOS視頻下載遇到的問題(附上AFHTTPRequestOperation下載視頻方法)
前言:
最近做即時聊天項目,涉及到視頻的上傳下載。AFNetworking上傳圖片和視頻(支援多張圖片上傳)
在視頻下載中遇到一些問題,視頻下載後無法播放
1 視頻下載方法
/** * 下載檔案 */- (void)downloadFileURL:(NSString *)aUrl savePath:(NSString *)aSavePath fileName:(NSString *)aFileName tag:(NSInteger)aTag{ NSFileManager *fileManager = [NSFileManager defaultManager]; //檢查本地檔案是否已存在 NSString *fileName = [NSString stringWithFormat:@%@/%@, aSavePath, aFileName]; //檢查附件是否存在 if ([fileManager fileExistsAtPath:fileName]) { NSData *audioData = [NSData dataWithContentsOfFile:fileName]; //...視頻下載完畢操作 }else{ //建立附件儲存目錄 if (![fileManager fileExistsAtPath:aSavePath]) { [fileManager createDirectoryAtPath:aSavePath withIntermediateDirectories:YES attributes:nil error:nil]; } //下載附件 NSURL *url = [[NSURL alloc] initWithString:aUrl]; NSURLRequest *request = [NSURLRequest requestWithURL:url]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; operation.inputStream = [NSInputStream inputStreamWithURL:url]; operation.outputStream = [NSOutputStream outputStreamToFileAtPath:fileName append:NO]; //下載進度控制 /* [operation setDownloadProgressBlock:^(NSUInteger bytesRead, long long totalBytesRead, long long totalBytesExpectedToRead) { NSLog(@is download:%f, (float)totalBytesRead/totalBytesExpectedToRead); }]; */ //已完成下載 [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSData *audioData = [NSData dataWithContentsOfFile:fileName]; //設定下載資料到res字典對象中並用代理返回下載資料NSData //...視頻下載完畢操作 } failure:^(AFHTTPRequestOperation *operation, NSError *error) { //下載失敗 //...視頻下載失敗操作 }]; [operation start]; }}
2 下載完視頻後,檔案沒有加尾碼.MP4 就會出現播放不了的情況,我的解決方案是,在上面的filename加一個尾碼.mp4,播放就ok了。