Skip to content

Instantly share code, notes, and snippets.

@wuyongrui
Created March 11, 2016 03:25
Show Gist options
  • Select an option

  • Save wuyongrui/4127d7221169bfe142d7 to your computer and use it in GitHub Desktop.

Select an option

Save wuyongrui/4127d7221169bfe142d7 to your computer and use it in GitHub Desktop.
Download a video and play with AVPlayer,AVPlayerLayer
class ViewController: UIViewController {
private var player:AVPlayer?
private var playerLayer:AVPlayerLayer?
override func viewDidLoad() {
super.viewDidLoad()
print(NSHomeDirectory())
}
@IBAction func download() {
let videoUrl = "http://7xp99e.com2.z0.glb.qiniucdn.com/2/video_article/6351A5E8_7F6C_4717_B91D_FE750634B5D5.mp4"
let documentPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, NSSearchPathDomainMask.AllDomainsMask, true).first!
let destPath = NSString(string: documentPath).stringByAppendingPathComponent("video.mp4") as String
if NSFileManager.defaultManager().fileExistsAtPath(destPath) {
print("file already exist at \(destPath)")
self.playVideo(NSURL(fileURLWithPath: destPath))
return
}
NSURLSession.sharedSession().downloadTaskWithURL(NSURL(string: videoUrl)!) { (location:NSURL?, response:NSURLResponse?, err:NSError?) -> Void in
if let _ = location {
do {
try NSFileManager.defaultManager().moveItemAtURL(location!, toURL: NSURL(fileURLWithPath: destPath))
self.playVideo(NSURL(fileURLWithPath: destPath))
}
catch let error as NSError {
print("move file error: \(error.localizedDescription)")
}
} else {
print("location err: \(location)")
}
}.resume()
}
private func playVideo(localPath:NSURL) {
self.player = AVPlayer(URL: localPath)
self.playerLayer = AVPlayerLayer(player: self.player)
self.playerLayer?.frame = self.view.frame
self.view.layer.addSublayer(self.playerLayer!)
self.player?.play()
}
}
// to support the http,open info.plist,add `App Transport Security Settings` then add `Allow Arbitrary Loads` item and set value `YES`
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment