我想保存之前从网址下载过的视频。 我使用此代码,当我点击下载按钮时,我将从URL下载视频。我使用连接方法,并在最后我使用NSFileManager保存视频数据。 问题是我创建了一个文件路径,但在其中没有任何类型的数据。我该如何解决?
-(IBAction)download:(id)sender{
/*[downloadButton setEnabled:NO];
[webView setUserInteractionEnabled:NO];*/
//Prendo URL
NSString *getURL = @"";
getURL = [webView stringByEvaluatingJavaScriptFromString:@"function getURL() {var player = document.getElementById('player'); var video = player.getElementsByTagName('video')[0]; return video.getAttribute('src');} getURL();"];
//Prendo il titolo
videoTitle = videoTitleField.text;
NSArray *components = [videoTitle componentsSeparatedByCharactersInSet:[[NSCharacterSet alphanumericCharacterSet] invertedSet]];
videoTitle = [components componentsJoinedByString:@" "];
if ([getURL length] > 0) {
if ([videoTitle length] > 0) {
//videoTitle = [getTitle retain];
fileURL = [NSURL URLWithString:getURL];
downloadUrl = fileURL;
bytesReceived = percentComplete = 0;
localFilename = [[[fileURL absoluteString] lastPathComponent] copy];
receivedData = [[NSMutableData alloc] initWithLength:0];
app.networkActivityIndicatorVisible = YES;
//Inserisco alert view
alert = [[UIAlertView alloc] initWithTitle:@"Download" message:[NSString stringWithFormat:@"%.2f",percentComplete] delegate:nil cancelButtonTitle:nil otherButtonTitles:nil];
[alert show];
//Connessione download
DownloadRequest = [[NSURLRequest alloc] initWithURL:fileURL cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:15];
DownloadConnection = [[NSURLConnection alloc] initWithRequest:DownloadRequest delegate:self startImmediately:YES];
}
else{
//Utente non inserisce il nome per il video
UIAlertView *alertview = [[UIAlertView alloc] initWithTitle:@"TubeDownloader" message:@"You have to insert a name for the video!" delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertview show];
}
}else {
//Non si riesce a prendere URL
UIAlertView *alertView1 = [[UIAlertView alloc] initWithTitle:@"TubeDownloader" message:@"Couldn't get MP4 URL." delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
[alertView1 show];
[downloadButton setEnabled:YES];
}
}
-(void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data{
if(!operationBreaked){
[self.receivedData appendData:data];
//[self.receivedData setData:data];
float receivedLen = [data length];
NSLog(@"receive lenght: %f\n",receivedLen);
bytesReceived = (bytesReceived + receivedLen);
if(expectedBytes != NSURLResponseUnknownLength){
//progressView.progress = ((bytesReceived/(float)expectedBytes)*100)/100;
percentComplete = (((bytesReceived/(float)expectedBytes)*100)/100) * 100;
}
NSLog(@"Ricevendo dati..percentuale di completamento:%f",percentComplete);
[alert setMessage:[NSString stringWithFormat:@"Percentage:%.2f",percentComplete]];
}else{
[connection cancel];
NSLog(@"Ricezione dati cancellata...percentuale:%f",percentComplete);
}
[self.receivedData appendData:data];
}
-(void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error{
operationFailed = YES;
//progressView.progress = 0.0;
}
-(void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response{
NSLog(@"Bytes aspettati: %f... Bytes ricevuti:%f\n",(float)expectedBytes,(float)bytesReceived);
NSHTTPURLResponse *r = (NSHTTPURLResponse*) response;//An NSHTTPURLResponse object represents a response to an HTTP URL load request. It’s a subclass of NSURLResponse that provides methods for accessing information specific to HTTP protocol responses.
NSDictionary *headers = [r allHeaderFields];//headerFields:a dictionary representing the keys and values from the server’s response header.
NSLog(@"[DO::didReceiveResponse] response headers: %@", headers);
if (headers){
if ([headers objectForKey: @"Content-Range"]) {
NSString *contentRange = [headers objectForKey: @"Content-Range"];
NSLog(@"Content-Range: %@", contentRange);
NSRange range = [contentRange rangeOfString: @"/"];
NSString *totalBytesCount = [contentRange substringFromIndex: range.location + 1];
expectedBytes = [totalBytesCount floatValue];
} else if ([headers objectForKey: @"Content-Length"]) {
NSLog(@"Content-Length: %@", [headers objectForKey: @"Content-Length"]);
expectedBytes = [[headers objectForKey: @"Content-Length"] floatValue];
} else expectedBytes = -1;
if ([@"Identity" isEqualToString: [headers objectForKey: @"Transfer-Encoding"]]) {
expectedBytes = bytesReceived;
operationFinished = YES;
}
}
}
-(void)connectionDidFinishLoading:(NSURLConnection *)connection{
NSLog(@"connessione terminata con successo receive data:%f!!",bytesReceived);
operationFinished = YES;
[alert setMessage:@"Download been succesfully"];
app.networkActivityIndicatorVisible = NO;
//NSData *saveData = [NSData dataWithBytes:&receivedData length:sizeof(receivedData)];
//Attivo timer per dimettere il timer
[NSTimer scheduledTimerWithTimeInterval:1 target:self selector:@selector(dismissAlert) userInfo:nil repeats:NO];
//[self.receivedData setData:];
//Chiamo la funzione di salvataggio passandogli come NSData receivedata e localfileName
//[self saveVideo:self.receivedData];
NSFileManager *fileManager = [NSFileManager defaultManager];
NSArray *path = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *pathdir = [NSString stringWithFormat:@"%@.mp4", [[path objectAtIndex:0] stringByAppendingPathComponent:videoTitle]];
NSLog(@"pathDir: %@",pathdir);
[fileManager createFileAtPath:pathdir contents:receivedData attributes:nil];
NSString *imagePath = [NSString stringWithFormat:@"%@.mp4", [[path objectAtIndex:0]stringByAppendingPathComponent:videoTitle]];
AVAsset *asset = [[AVURLAsset alloc] initWithURL:[NSURL fileURLWithPath:[NSString stringWithFormat:@"%@.mp4",[[path objectAtIndex:0] stringByAppendingPathComponent:videoTitle]]] options:nil]; //AVAsset is an abstract class to represent timed audiovisual media such as videos and sounds. Each asset contains a collection of tracks that are intended to be presented or processed together, each of a uniform media type, including but not limited to audio, video, text, closed captions, and subtitles.
AVAssetImageGenerator *imageGenerator = [[AVAssetImageGenerator alloc] initWithAsset:asset]; //An AVAssetImageGenerator object provides thumbnail or preview images of assets independently of playback. AVAssetImageGenerator uses the default enabled video track(s) to generate images.
Float64 durationSeconds = CMTimeGetSeconds(asset.duration);
CMTime midpoint = CMTimeMakeWithSeconds(durationSeconds / 2.0, 600);
CMTime actualTime;
CGImageRef preImage = [imageGenerator copyCGImageAtTime:midpoint actualTime:&actualTime error:NULL];
if (preImage != NULL) {
CGRect rect = CGRectMake(0.0, 0.0, CGImageGetWidth(preImage) * 0.5, CGImageGetHeight(preImage) * 0.5);
UIImage *image = [UIImage imageWithCGImage:preImage];
UIGraphicsBeginImageContext(rect.size);
[image drawInRect:rect];
NSData *data = UIImagePNGRepresentation(UIGraphicsGetImageFromCurrentImageContext());
[fileManager createFileAtPath:imagePath contents:data attributes:nil];
UIGraphicsEndImageContext();
}
CGImageRelease(preImage);
//videoTitle = nil;
NSLog(@"Salvataggio con successo");
}