我想将视频从网址保存到目录,并在应用程序中显示在图库中。
以下是我的代码:
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 :(得分: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
}
答案 1 :(得分:0)
假设网址直接指向视频,您只需创建NSURLSessionDownloadTask
即可将视频数据下载到文件系统中,完成下载后,可通过为本地视频创建AVPlayerItem来打开视频。 / p>