alish
alish

Reputation: 1

Retrieving video file stored as PFFile for ios application developed in swift

Have a parse class "Response", with one of the fields being of type File. Am uploading the files to this column for each row manually by selecting the cell and clicking "upload a file".

Now I need to get this file (which as I understand should be PFFile type) and play this file (its a video file) in my iOS app.

Please help!

Upvotes: 0

Views: 916

Answers (1)

kev8484
kev8484

Reputation: 648

Assuming you just want to stream the video file and not actually download it (which may take a while), you simply need to fetch the PFObject in your "Response" class. Once you have the object, you can get a reference to the PFFile where the video is saved and access its URL property:

// define these as class properties:
var player:AVPlayer!
var playerLayer:AVPlayerLayer!

// write all of the below somewhere in your ViewController, e.g. in viewDidLoad:
var videoUrl:String!

let query = PFQuery(className: "Response")
query.getObjectInBackgroundWithId("objectId123") {
    (object:PFObject?, error:NSError?) in
    if (error == nil && object != nil) {
        let videoFile = object!["keyForVideoPFFile"] as! PFFile
        videoUrl = videoFile.url
        self.setupVideoPlayerWithURL(NSURL(string: videoUrl)!)
    }
}

In the above code, you feed the video's URL to an AVPlayer object which will stream the video. Note that you need to import AVKit to use AVPlayer and AVPlayerLayer. The function for setting up the player is as follows:

func setupVideoPlayerWithURL(url:NSURL) {

    player = AVPlayer(URL: url)
    playerLayer = AVPlayerLayer(player: self.player)
    playerLayer.videoGravity = AVLayerVideoGravityResizeAspect
    playerLayer.frame = self.view.frame   // take up entire screen
    self.view.layer.addSublayer(self.playerLayer)
    player.play()
}

I would recommend checking out Apple's docs on AVPlayer and AVPlayerLayer to learn more about video playback.

AVPlayer: https://developer.apple.com/library/prerelease/ios/documentation/AVFoundation/Reference/AVPlayer_Class/index.html

AVPlayerLayer: https://developer.apple.com/library/prerelease/ios/documentation/AVFoundation/Reference/AVPlayerLayer_Class/index.html#//apple_ref/occ/cl/AVPlayerLayer

Upvotes: 1

Related Questions