I'm trying to compress videos selected from the photo library of the iPhone device and uploading them to the server. Its working for all devices except iPhone 12. On iPhone 12 videos are showing all blue and same to server. Following is the code I'm using to compress videos.
func convertVideo(phAsset : PHAsset, handler:@escaping (_ compressedData: Data?)-> Void){
var compressedData: Data? = nil
PHImageManager.default().requestAVAsset(forVideo: phAsset, options: PHVideoRequestOptions(), resultHandler: { (asset, audioMix, info) -> Void in
if let asset = asset as? AVURLAsset {
do {
let videoData = try Data.init(contentsOf: asset.url)
print(asset.url)
//self.orginalVideo = asset.url
print("File size before compression: \(Double(videoData.count / 1048576)) mb")
let compressedURL = NSURL.fileURL(withPath: NSTemporaryDirectory() + NSUUID().uuidString + ".MP4")
print(compressedURL)
self.compressVideo(inputURL: asset.url , outputURL: compressedURL) { (exportSession) in
guard let session = exportSession else {
return
}
switch session.status {
case .unknown:
print("unknown")
handler(compressedData)
break
case .waiting:
print("waiting")
handler(compressedData)
break
case .exporting:
print("exporting")
handler(compressedData)
break
case .completed:
do {
compressedData = try Data.init(contentsOf: compressedURL)
//self.compressVideo = compressedURL
print("File size AFTER compression: \(Double(compressedData!.count / 1048576)) mb")
handler(compressedData)
}
catch{
print(error)
handler(compressedData)
}
case .failed:
print("failed")
handler(compressedData)
break
case .cancelled:
print("cancelled")
handler(compressedData)
break
@unknown default:
break
}
}
} catch {
print(error)
handler(compressedData)
//return
}
}
})
}
func compressVideo(inputURL: URL, outputURL: URL, handler:@escaping (_ exportSession: AVAssetExportSession?)-> Void) {
let urlAsset = AVURLAsset(url: inputURL, options: nil)
guard let exportSession = AVAssetExportSession(asset: urlAsset, presetName: AVAssetExportPresetMediumQuality) else {
handler(nil)
return
}
exportSession.outputURL = outputURL
exportSession.outputFileType = AVFileType.mp4
exportSession.shouldOptimizeForNetworkUse = true
exportSession.exportAsynchronously { () -> Void in
handler(exportSession)
}
}
Please help. Thanks in advance!
Resolved it by using LightCompressor_ios lib https://github.com/AbedElazizShe/LightCompressor_iOS