从视频网址下载视频

时间:2013-09-06 10:40:19

标签: iphone ios ios6 ios4

我想从网址下载视频。我有视频网址,但不知道如何下载。

- (void)viewDidLoad
{
    [super viewDidLoad];
    // Do any additional setup after loading the view from its nib.

    strFileName = @"MyVideo";

    NSMutableURLRequest *request = [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:@"http://www.youtube.com/v/P9MeXRzKUuA?version=3&f=videos&app=youtube_gdata"]]; //strFileURL is url of your video/image
    NSURLConnection *conection = [[[NSURLConnection alloc] initWithRequest:request delegate:self startImmediately:YES] autorelease];
    [conection start];
    [request release];

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

    NSLog(@"file path = %@",strFilePath);
}

- (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSURLResponse *)response
{
// create
NSLog(@"file path = %@",strFilePath);
if (![[NSFileManager defaultManager] fileExistsAtPath:strFilePath]) {
    [[NSFileManager defaultManager] createFileAtPath:strFilePath contents:nil attributes:nil];
}

file = [[NSFileHandle fileHandleForUpdatingAtPath:strFilePath] retain];// read more about file handle
if (file)   {
    [file seekToEndOfFile];
}
NSLog(@"response received");

[responseData setLength:0];

}

- (void)connection:(NSURLConnection *)connection didReceiveData:(NSData *)receivedata
{
//write each data received
if( receivedata != nil){
    if (file)  {
        [file seekToEndOfFile];
    }
    [file writeData:receivedata];
    NSLog(@"data received");

}
[responseData appendData:receivedata];
}

- (void)connectionDidFinishLoading:(NSURLConnection*)theConnection {
//close file after finish getting data;

NSLog(@"response = %@",[[NSString alloc] initWithData:responseData encoding:NSUTF8StringEncoding]);

[file closeFile];
NSLog(@"file closed");

NSURL *fileURL = [NSURL fileURLWithPath:strFilePath];

NSLog(@"fileurl = %@",fileURL);
[webView loadRequest:[NSURLRequest requestWithURL:fileURL]];

}

在我打印响应的connectiondidfinishedloading方法中,它为空。

请帮我解决这个问题

1 个答案:

答案 0 :(得分:0)

您忘记初始化responseData变量。请这样做。