Swift get NSData of a video from photos library

2019-03-31 01:45发布

问题:

Im using UIImagePickerController to select a video from my library. I need to extract the NSData of my video file. Im using the following operation to select a video from my library but my data appears to be nil however my AVPlayer plays the video from the resulting NSURL so I know problem is not with the NSURL. How can I extract the NSData of my selected video file?

func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: [String : AnyObject]) {
    let fileURL = info[UIImagePickerControllerReferenceURL] as! NSURL!

    let data = NSData(contentsOfURL: fileURL)
    print(data)

    player = AVPlayer(URL: fileURL)
    let playerLayer = AVPlayerLayer(player: player)
    playerLayer.frame = CGRectMake(0, 0, 300, 300)
    self.view.layer.addSublayer(playerLayer)
    player.play()

    self.dismissViewControllerAnimated(true, completion: nil)
}

回答1:

Try changing UIImagePickerControllerReferenceURL to

UIImagePickerControllerMediaURL

Instead of let data = NSData(contentsOfURL: fileURL)

let video3 = try NSData(contentsOfURL: videoDataURL, options: .DataReadingMappedIfSafe)