由于内存警告,当我从照片库中选择多个视频(每个 1 分钟以上)时,我的应用程序崩溃了。我正在尝试压缩视频,但尽管压缩代码工作正常,但仍然是同样的问题。我希望我的应用一次选择 5 个视频并在聊天中发送它们。Whatsapp 允许用户选择 30 个视频并在聊天中发送它们,但我的应用程序由于仅在 3 个视频后出现内存问题而崩溃。我正在使用“AssetsPickerViewController”库进行多个图片/视频选择。
func assetsPicker(controller: AssetsPickerViewController, selected assets: [PHAsset]) {
self.dismiss(animated: true, completion: nil)
var isImages = false
var mediaData: [Data] = []
let imageManager = PHCachingImageManager.default()
DispatchQueue.main.async {
self.appDelegate.helper.showHUD(withMessage: "Preparing media", withObject: self)
}
autoreleasepool {
for selectedAsset in assets {
if selectedAsset.mediaType == .image {
isImages = true
let option = PHImageRequestOptions()
option.isSynchronous = true
option.isNetworkAccessAllowed = true
imageManager.requestImageData(for: selectedAsset, options: option) { (assetData, assetDataUTI, assetOrientation, assetInfo) in
if let data = assetData {
if let image = UIImage(data: data)?.upOrientation(), let finalData = image.jpegData(compressionQuality: 0.5) {
if let newData = ImageHelper.removeExifData(data: finalData as NSData) {
mediaData.append(newData as Data)
self.checkFileStatus(mediaCount: mediaData.count, assetsCount: assets.count, data: mediaData, isImages: isImages)
} else {
mediaData.append(finalData)
self.checkFileStatus(mediaCount: mediaData.count, assetsCount: assets.count, data: mediaData, isImages: isImages)
}
} else {
mediaData.append(data)
self.checkFileStatus(mediaCount: mediaData.count, assetsCount: assets.count, data: mediaData, isImages: isImages)
}
}
}
} else if selectedAsset.mediaType == .video {
let options: PHVideoRequestOptions = PHVideoRequestOptions()
options.isNetworkAccessAllowed = true
options.deliveryMode = .fastFormat
self.convertVideo(phAsset: selectedAsset) { (data) in
if let finalData = data {
mediaData.append(finalData)
self.checkFileStatus(mediaCount: mediaData.count, assetsCount: assets.count, data: mediaData, isImages: isImages)
} else {
}
}
}
}
}
}
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)
}
}