从给定的URL下载视频文件

时间:2015-02-12 12:59:17

标签: objective-c iphone

我想在我的iPhone应用程序中从给定的URL下载视频和音频文件,并且还想显示下载的进度。

使用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");
    }
}

它回调connectionDidFinishLoading并在本地保存结果,但是当我检查文件时,它的持续时间为0.0。我做错了什么?

1 个答案:

答案 0 :(得分:1)

要在您的应用中下载包含YouTube中的任何内容,您需要首先集成他们的API / iFrame。

YouTube API integration docs

您对YouTube视频的网址仅仅是对视频的引用,而不是实际的视频数据本身。你提到你已经以这种方式下载了像PDF这样的其他文件,你可能会看到他们的网址末尾附有pdf,表示它是PDF格式的网址。 YouTube网址没有。

我希望此链接有所帮助。