Reputation: 327
I want to download a video and audio file from a given URL in my iPhone app and also want to show the progress of the download.
Using NSUrlConnection
:
- (IBAction)startDownloading:(id)sender {
downlodStatus.progress=0;
currentURL=@"https://www.youtube.com/watch?v=Hgr4tyZvPDY";
NSURL *url = [NSURL URLWithString:currentURL];
NSURLRequest *theRequest = [NSURLRequest requestWithURL:url cachePolicy:NSURLRequestReloadIgnoringLocalCacheData timeoutInterval:60];
receivedData = [[NSMutableData alloc] initWithLength:0];
NSURLConnection * connection = [[NSURLConnection alloc] initWithRequest:theRequest delegate:self startImmediately:YES];
[connection start];
}
- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response {
[UIApplication sharedApplication].networkActivityIndicatorVisible = YES;
downlodStatus.hidden = NO;
expectedBytes = [response expectedContentLength];
}
- (void) connection:(NSURLConnection *)connection didReceiveData:(NSData *)data {
[receivedData appendData:data];
float progressive = (float)[receivedData length] / (float)expectedBytes;
[downlodStatus setProgress:progressive];
}
- (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
}
- (NSCachedURLResponse *) connection:(NSURLConnection *)connection willCacheResponse: (NSCachedURLResponse *)cachedResponse {
return nil;
}
- (void) connectionDidFinishLoading:(NSURLConnection *)connection {
downlodStatus.progress=1.0;
NSArray *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
NSString *documentsDirectory = [paths objectAtIndex:0];
NSString *pdfPath = [documentsDirectory stringByAppendingPathComponent:[@"new" stringByAppendingString:@".mp4"]];
[UIApplication sharedApplication].networkActivityIndicatorVisible = NO;
if ([receivedData writeToFile:pdfPath atomically:YES]) {
NSLog(@"save successfully");
}
else
{
NSLog(@"can not save file");
}
}
It makes a callback to connectionDidFinishLoading
and I save the result locally but when I check the file it has a duration of 0.0. What am I doing wrong?
Upvotes: 0
Views: 378
Reputation: 4105
In order to download incorporate anything from YouTube within your app you'll need to integrate their API/iFrame first.
The URL you have for the YouTube video is merely a reference to a video, not the actual video data itself. You mention you've downloaded other files like PDF's in this manner, which you will likely see their url's are appended with pdf on the end to signify it's a url to a pdf. The YouTube url doesn't.
I hope this link helps.
Upvotes: 1