Я взял ответ @kgutteridge и сделал аналогичное решение для Swift 3.0 , используя рекурсив:
extension UIImage {
static func compress(image: UIImage, maxFileSize: Int, compression: CGFloat = 1.0, maxCompression: CGFloat = 0.4) -> Data? {
if let data = UIImageJPEGRepresentation(image, compression) {
let bcf = ByteCountFormatter()
bcf.allowedUnits = [.useMB] // optional: restricts the units to MB only
bcf.countStyle = .file
let string = bcf.string(fromByteCount: Int64(data.count))
print("Data size is: \(string)")
if data.count > (maxFileSize * 1024 * 1024) && (compression > maxCompression) {
let newCompression = compression - 0.1
let compressedData = self.compress(image: image, maxFileSize: maxFileSize, compression: newCompression, maxCompression: maxCompression)
return compressedData
}
return data
}
return nil
}
}