How to download video from url and save it in to document directory in iOS?

前端 未结 4 1838
旧巷少年郎
旧巷少年郎 2021-01-03 12:57

How to download video from url and save it in to document directory in iOS

4条回答
  •  孤城傲影
    2021-01-03 13:23

    use this code it is working in my current project

    -(void)DownloadVideo
    {
    //download the file in a seperate thread.
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    NSLog(@"Downloading Started");
    NSString *urlToDownload = @"http://www.somewhere.com/thefile.mp4";
    NSURL  *url = [NSURL URLWithString:urlToDownload];
    NSData *urlData = [NSData dataWithContentsOfURL:url];
    if ( urlData )
        {
        NSArray       *paths = NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES);
        NSString  *documentsDirectory = [paths objectAtIndex:0];
    
        NSString  *filePath = [NSString stringWithFormat:@"%@/%@", documentsDirectory,@"thefile.mp4"];
    
        //saving is done on main thread
        dispatch_async(dispatch_get_main_queue(), ^{
            [urlData writeToFile:filePath atomically:YES];
            NSLog(@"File Saved !");
        });
        }
    
    });
    }
    

提交回复
热议问题