0

I would like to save video from url to directory and show in gallery in application.

Below is my code:

import UIKit
import AVFoundation
import AVKit

class SettingsViewController: UIViewController {

    @IBOutlet var urlLabel: UITextField!
    let PlayerController = AVPlayerViewController()
    var Player:AVPlayer?

    //
    //    override func viewDidLoad() {
    //        super.viewDidLoad()
    //
    //    }
    //    override func didReceiveMemoryWarning() {
    //        super.didReceiveMemoryWarning()
    //        // Dispose of any resources that can be recreated.
    //    }
    //

    @IBAction func downloadButton(sender: AnyObject) {

        let urlLabel1 = urlLabel.text
        let videoURL:NSURL? = NSURL(string: urlLabel1!)

        if let url = videoURL {
            self.Player = AVPlayer(URL: url)
            self.PlayerController.player = self.Player
            self.presentViewController(self.PlayerController, animated: true) { self.PlayerController.player?.play()}
            print("work")
        }
        else {
            var refreshAlert = UIAlertController(title: "Error", message: "Please correct your URL", preferredStyle: UIAlertControllerStyle.Alert)
            refreshAlert.addAction(UIAlertAction(title: "Ok", style: .Default, handler: { (action: UIAlertAction!) in
                print("Handle Ok logic here")
            }))
            presentViewController(refreshAlert, animated: true, completion: nil)

            print("not work")
        }
    }
}

Any ideas how can I make it?

Dharmesh Kheni
  • 71,228
  • 33
  • 160
  • 165
mechu911
  • 426
  • 4
  • 15

2 Answers2

2
//Save Video to Home Directory 
func saveVideoFromURL(videoURL: NSURL, name: String) {
    let homeDirectory = NSURL.fileURLWithPath(NSHomeDirectory(), isDirectory: true)
    let fileURL = homeDirectory.URLByAppendingPathComponent(name).URLByAppendingPathComponent("mov")

    let urlData = NSData(contentsOfURL: videoURL)
    urlData?.writeToURL(fileURL, atomically: true)
}

//Extract video from home directory
func getVideoFromDirectoryWithName(name: String) -> NSData {
    let homeDirectory = NSURL.fileURLWithPath(NSHomeDirectory(), isDirectory: true)
    let fileURL = homeDirectory.URLByAppendingPathComponent(name).URLByAppendingPathComponent("mov")

    let fileData = NSData(contentsOfURL: fileURL)!
    return fileData
}
BenJammin
  • 1,479
  • 13
  • 18
0

Assuming the URL points directly to the video, you could simply create a NSURLSessionDownloadTask to download the video data onto the filesystem, and upon completing the download, open the video by creating an AVPlayerItem for the local video.

dzl
  • 908
  • 11
  • 32