[英]iOS : How to convert a video PHAsset to NSData
I want to put the videos stored on my iPhone to my Google Drive.我想将存储在 iPhone 上的视频放到我的 Google 云端硬盘中。 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 :对于图像,没问题,我使用以下方法将我的资产转换为 NSData:
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 !之后,你就有了好的 NSData 变量,你可以用它把你的视频放到云端!
if you miss option.isNetworkAccessAllowed = true then you get error for genera the url如果你错过 option.isNetworkAccessAllowed = true 那么你会得到 url 属的错误
private let options: PHVideoRequestOptions = PHVideoRequestOptions()
option.isNetworkAccessAllowed = true
PHImageManager.default().requestAVAsset(-------
Updated for Swift 5为 Swift 5 更新
PHImageManager
or PHCachingImageManager
can be used here这里可以使用
PHImageManager
或PHCachingImageManager
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同步获取图像/视频 Swift 5 + 缓存
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
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.