2016-08-22 43 views
0

我想將視頻從網址保存到目錄並在應用程序中顯示在圖庫中。如何從url中保存視頻目錄?

下面是我的代碼:

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") 
     } 
    } 
} 

任何想法如何,我能做到嗎?

回答

0

假設URL直接指向視頻,您可以簡單地創建一個NSURLSessionDownloadTask以將視頻數據下載到文件系統,並且在完成下載後,通過爲本地視頻創建AVPlayerItem來打開視頻。

1
//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 
} 
相關問題