前言
最近做项目,使用到了PHAseet,因为ALAsset已经废弃了.实话说,PHAseet现在比ALAsset麻烦,获取地址路径就很恶心,总之,一点点也是趟过来了,做个记录,以后自己别忘了.
获取图片,获取视频首帧
let option = PHImageRequestOptions()
option.isNetworkAccessAllowed = true //允许下载iCloud的图片
option.resizeMode = .fast
option.deliveryMode = .fastFormat
PHImageManager.default().requestImage(for: asset,
targetSize: self.bounds.size,
contentMode: .aspectFill,
options: option)
{ (image, nil) in
//image就是图片
}
获取视频
let options = PHVideoRequestOptions()
options.isNetworkAccessAllowed = true
options.deliveryMode = .automatic
PHImageManager.default().requestPlayerItem(forVideo:asset, options: options, resultHandler: { playerItem, info in
guard self.playerLayer == nil else { return }
//播放视频
let player = AVPlayer(playerItem: playerItem)
let playerLayer = AVPlayerLayer(player: player)
playerLayer.videoGravity = AVLayerVideoGravity.resizeAspect
playerLayer.frame = self.layer.bounds
self.contentView.layer.insertSublayer(playerLayer, below: self.palyBtn.layer)
player.play()
self.playerLayer = playerLayer
})
注意事项
使用的时候,尽量将option.isNetworkAccessAllowed = true
打开, 允许下载iCloud的图片和视频,否则会照成crash.这块当时给我弄的很无奈,因为我好几个地方都上传图片,改了好几遍.
将PHAsset转化为视频的NSData
我自己封装了一个简单的类,代码入下
import UIKit
import Photos
class XXVideoCompression: NSObject {
public func compressVideo(_ exportSession:AVAssetExportSession? , completion: @escaping (_ data: Data)-> Void) {
let uuu = self.compressedUrl()
exportSession?.outputURL = URL.init(fileURLWithPath: uuu)
exportSession?.outputFileType = .mp4
exportSession?.shouldOptimizeForNetworkUse = true;
if let assetTime = exportSession?.asset.duration {
let duration = CMTimeGetSeconds(assetTime)
print("视频时长 \(duration)");
}
exportSession?.exportAsynchronously(completionHandler: {
switch exportSession?.status{
case .failed?:
print("失败...\(String(describing: exportSession?.error?.localizedDescription))")
completion(Data())
break
case .cancelled?:
print("取消")
completion(Data())
break;
case .completed?:
print("转码成功")
do {
let data = try Data.init(contentsOf: URL.init(fileURLWithPath: uuu), options: Data.ReadingOptions.init())
let mp4Path = URL.init(fileURLWithPath: uuu)
let size = self.fileSize(url: mp4Path)
print("视频时长\(size)")
completion(data)
} catch let error {
print("失败 \(error)")
completion(Data())
}
break;
default:
print("..")
completion(Data())
break;
}
})
}
//保存压缩
func compressedUrl() -> String {
let string = NSHomeDirectory() + "/Documents/\(Date().timeIntervalSince1970).mp4"
return string//URL.init(fileURLWithPath: string)
}
//计算视频大小
func fileSize(url:URL) -> CGFloat {
return CGFloat(NSData.init(contentsOf: url)?.length ?? 0 )/// 1024 / 1024
}
//获取视频首帧
func imageWithVideoUrl(mediaModel:HEPhotoAsset,completion: @escaping ( _ image:UIImage) -> Void) {
let option = PHImageRequestOptions()
option.isNetworkAccessAllowed = true
option.resizeMode = .fast
option.deliveryMode = .fastFormat
PHImageManager.default().requestImage(for: mediaModel.asset,
targetSize:PHImageManagerMaximumSize,
contentMode: .aspectFill,
options: option )
{ (image, info) in
completion(image ?? UIImage())
}
}
}
具体使用如下:
//
let options = PHVideoRequestOptions()
options.isNetworkAccessAllowed = true
options.deliveryMode = .automatic
PHImageManager.default().requestExportSession(forVideo: mediaModel.asset, options: options, exportPreset: AVAssetExportPresetMediumQuality) { (exportSession, info) in
//将asset转换为AVAssetExportSession对象,用AVAssetExportSession转化为Data
XXVideoCompression().compressVideo(exportSession, completion: { (data) in
if data.count > 0 {//做判断,判断是否转化成功
//进行视频上传
}
}
}
具体问题具体分析,使用过程中,总会遇到各种各样的问题,但是只要有耐心,总会一点点解决的.欢迎各位留言,提问.
如果我的文章,对你有帮助,请给我一个👍哦~~!
网友评论