Haroon Ahmed Haroon Ahmed - 1 year ago 100
Swift Question

Is this possible to play Video File synchronous downloading with Almofire?

I try to download file using

and I done that with progress. What I am trying to do now is building a type of local stream from video URL.

Alamofire store the downloaded file at destination.

let destination = Alamofire.Request.suggestedDownloadDestination(directory: .DocumentDirectory, domain: .LocalDomainMask)

This destination is not valid to play in my case. eg.

if totalBytesRead >= 51831 {
let player = AVPlayer(URL: NSURL(fileURLWithPath: "\(destination)"))
let playerController = AVPlayerViewController()
playerController.player = player
self.presentViewController(playerController, animated: true) {

Is there another way to do this ? OR can I store downloaded bytes to an array/buffer ?


Answer Source

You don't need Alamofire in order to stream content which is in your case a video.

You can actually utilize existing Apple's classes such as:

Using those 3 classes you can create your own class like VideoPlayer that will use them for streaming.

Here's a code snip for the constructor to get you started:

playerItem = AVPlayerItem(URL: videoURL)
player = AVPlayer(playerItem: self.playerItem!)
playerLayer = AVPlayerLayer(player: self.player)
playerLayer?.frame = newFrame
playerLayer?.videoGravity = AVLayerVideoGravityResizeAspect

Now, you can use this class inside another View Controller:


This will add the video player class you created and now you only need to play the video:

// Of type AVPlayer

This is the easy part, if you want you will have to to implement your own buffer & rate and of course implement an observer to observe the rate and buffer:

 // Observe the Rate of the player. when the video playing or paused
 player.addObserver(theSelf, forKeyPath: "rate", options: .New, context: nil)
 // Observe when the Video player Buffer is empty
 playerItem.addObserver(theSelf, forKeyPath: "playbackBufferEmpty", options: .New, context: nil)
 // Observe the loaded Buffer of the video
 playerItem.addObserver(theSelf, forKeyPath: "loadedTimeRanges", options: NSKeyValueObservingOptions.New, context: nil)

Also, don't forget to remove them when you are done with them.

Good luck.