我一直在努力解决这个问题令人作呕,但仍然无法弄清楚导致崩溃的原因。我从按钮实例化相机,此后当用户选择照片时,我将照片添加到我的images阵列并重新加载collectionView。大约20次后,我得到控制台中的输出“资产连接中断或资产死亡”,随后发生崩溃。当我从委托方法“didFinishPickingMediaWithInfo”中删除collectionView?.reloadData()方法时,它不会崩溃。这让我非常混淆。请参阅以下代码:
func imagePickerController(picker: UIImagePickerController, didFinishPickingMediaWithInfo info: Dictionary) {
if let image = info["UIImagePickerControllerOriginalImage"] as? UIImage {
images.append(image)
// when i remove this method the app doesnt crash!
collectionView.reloadData()
collectionView?layoutIfneeded()
dismiss(animated: true, completion: nil)
}
这是解决方案,请注意压缩大小是硬编码的,您可能希望根据需要调整代码或重构并改进方法。
func imageCompression(_ imageDict: [String : UIImage]) -> [String : Data] {
var compressedImages = [String : Data]()
for (key, value) in imageDict {
var resizeAttempts = 5
var compressionRatio: CGFloat = 1
var imageData = UIImageJPEGRepresentation(value, compressionRatio)
if imageData?.count <= 90000 {
compressedImages[key] = imageData
} else {
while imageData?.count > 90000 && resizeAttempts > 0 {
resizeAttempts -= 1
compressionRatio = compressionRatio * 0.5
imageData = UIImageJPEGRepresentation(value, compressionRatio)
compressedImages[key] = imageData
print("image size now is \(imageData?.count)")
}
}
}
return compressedImages
}