简体   繁体   中英

iOS : How to convert a video PHAsset to NSData

I want to put the videos stored on my iPhone to my Google Drive. I have already done with images, but with videos, it's an other problem...

For images, no problem, I convert my asset to an NSData with this method :

   data = UIImagePNGRepresentation(result!)!

And I put the image to my drive !

But, for videos, I tried many different ways, but no, I can't.

How can I do ?

Thanks a lot !

I did it !

This is the solution :

    PHCachingImageManager().requestAVAssetForVideo(asset, options: nil, resultHandler: {(asset: AVAsset?, audioMix: AVAudioMix?, info: [NSObject : AnyObject]?) in
        dispatch_async(dispatch_get_main_queue(), {

            let asset = asset as? AVURLAsset
            var data = NSData(contentsOfURL: asset.URL)
    })
})

And after, you have the good NSData variable which you can use to put your video to the Cloud !

Please add Bellow solution its work for me

if you miss option.isNetworkAccessAllowed = true then you get error for genera the url

private let options: PHVideoRequestOptions = PHVideoRequestOptions()

option.isNetworkAccessAllowed = true 

PHImageManager.default().requestAVAsset(-------

Updated for Swift 5

PHImageManager or PHCachingImageManager can be used here

PHImageManager.default().requestAVAsset(forVideo: asset,
                                        options: nil) { (asset, audioMix, info) in
     if 
         let asset = asset as? AVURLAsset,
         let data = NSData(contentsOf: asset.url) {
             //do smth with data
         }
      }
                                                        
}

Fetch synchronously Image/Video Swift 5 + caching

extension PHAsset {
    func getImage() -> UIImage? {
        let manager = PHCachingImageManager.default
        let option = PHImageRequestOptions()
        option.isSynchronous = true
        var img: UIImage? = nil
        manager().requestImage(for: self, targetSize: CGSize(width: self.pixelWidth, height: self.pixelHeight), contentMode: .aspectFit, options: nil, resultHandler: {(result, info) -> Void in
            img = result!
        })
        return img
    }

    func getVideo() -> NSData? {
        let manager = PHCachingImageManager.default
        let option = PHImageRequestOptions()
        option.isSynchronous = true
        var resultData: NSData? = nil
    
        manager().requestAVAsset(forVideo: self, options: nil) { (asset, audioMix, info) in
            if let asset = asset as? AVURLAsset, let data = NSData(contentsOf: asset.url) {
                resultData = data
            }
        }
        return resultData
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM