iOS – 下载video

我想从远程URL下载video并将其保存到iPhone应用程序中的文件。 我知道video链接的作品,因为我用AVPlayer,但是,我无法下载它。 响应总是(空)。

下面的代码有什么问题?

NSURLRequest *request = [NSURLRequest requestWithURL:[NSURL URLWithString:someURLString]]; AFHTTPRequestOperation *operation = [[AFHTTPRequestOperation alloc] initWithRequest:request]; operation.outputStream = [NSOutputStream outputStreamToFileAtPath:someFilePath append:NO]; [operation setCompletionBlockWithSuccess:^(AFHTTPRequestOperation *operation, id responseObject) { NSLog(@"Successfully downloaded file to %@", [NSURL fileURLWithPath:someFilePath]); NSLog(@"THE RESPONSE: %@", responseObject); } failure:^(AFHTTPRequestOperation *operation, NSError *error) { NSLog(@"Error: %@", error); }]; [operation start]; 

更新

我注释掉了operation.outputStream行,这次我得到了一个响应。 这是否意味着文件path有问题?

只需创build一个链接到该文件,然后使用NSURLConnection下载。

创build一个URL连接来下载:

 NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init]; [request setURL:[NSURL URLWithString:strFileUrl]]; //strFileURL is url of your video/image NSURLConnection *conection = [[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:NO] autorelease]; [conec start]; [request release]; 

获取文件path来保存数据:

 strFilePath = [[NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) objectAtIndex:0] stringByAppendingPathComponent:strFileName]; 

你的类必须采用NSURLConnectionDelegate协议的3种方法:(请阅读协议和委托)

  - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response { // create [[NSFileManager defaultManager] createFileAtPath:strFilePath contents:nil attributes:nil]; file = [[NSFileHandle fileHandleForUpdatingAtPath:strFilePath] retain];// read more about file handle if (file) { [file seekToEndOfFile]; } } - (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)receivedata { //write each data received if( receivedata != nil){ if (file) { [file seekToEndOfFile]; } [file writeData:receivedata]; } } - (void)connectionDidFinishLoading:(NSURLConnection*)theConnection { //close file after finish getting data; [file closeFile]; } - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error { //do something when downloading failed } 

如果你想查看你的文件,使用一个UIWebview加载它:

  NSURL *fileURL = [NSURL fileURLWithPath:strFilePath]; [wvReview loadRequest:[NSURLRequest requestWithURL:fileURL]]; 

这是什么问题。

我正在使用video的url,并作为文件path的一部分。

为什么这是错的? 它有反斜杠,所以我认为iOS变得困惑。

获得的经验:确保添加到目录以创build文件的string没有反斜杠。

我希望这能帮助任何犯这个愚蠢错误的人。 :P