need to convert a video file to NSData and then back to playable URL. The NSData portion is as follows:
let videoNSD = NSData(contentsOfURL: videoPreview!)
// videoNSD is uploaded to cloud and then retrieved..
func playNSDataVideoPreview(videoNSD: NSData)
{
// how to play in AVPlayer?
let playerController = AVPlayerViewController()
let paths = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true)
let documentsDirectory = paths[0]
let filePath = documentsDirectory + "/" + "nsdfile-1234.mp4"
let nsdURL = NSURL(fileURLWithPath: filePath)
videoNSD.writeToURL(nsdURL, atomically: true)
mediaPlayer = AVPlayer(URL: nsdURL)
playerController.player = mediaPlayer
mediaPlayer.play()
}
What is the best practice for playing in AVPlayer?
Thanks...
First of all, I'd suggest to Upload/Download as file ( from File handle ) and not Data ( NSData ) , because videos might be bigger than RAM ( imagine a movie ).
To download File with Alamofire , you can use sample code from https://github.com/Alamofire/Alamofire#downloading
Alamofire.download(.GET, "http://httpbin.org/stream/100") { temporaryURL, response in
let fileManager = NSFileManager.defaultManager()
let directoryURL = fileManager.URLsForDirectory(.DocumentDirectory, inDomains: .UserDomainMask)[0]
let pathComponent = response.suggestedFilename
return directoryURL.URLByAppendingPathComponent(pathComponent!)
}
after downloading and having a file, you can directly use AVPlayer(URL URL: NSURL)
If you have just NSData of video and want to play it, first save it as file and then create AVPlayer
with your saved URL ( file location )
YOURVIDEODATA.writeToURL(URL_WHERE_TO_SAVE,atomically: true)
and then again use AVPlayer(URL: URL_WHERE_TO_SAVE)