我使用 Alamofire 与 MultiParts 将图片从我的应用程序上传到我的服务器,但是当我执行该过程时,我的应用程序崩溃并显示消息:
“由于内存问题而终止”
我知道问题是,当我 getUIImageFromPHAsset 时,它会导致应用程序出现内存错误 - 我的图像太大(80mb-36图像)。但我不知道如何解决它。
以下是代码:
将图片上传到服务器:
self.getUIImageFromPHAsset(assets: self.phAssets, completion: { (images) in
self.uploadingView.isHidden = false
self.restApiManager.requestCreateProduct(username: _username, product: _product, images: images)
})
从PHAsset获取UIImage:
func getUIImageFromPHAsset(assets: [PHAsset], completion: @escaping ( (_ images:[UIImage]) -> ())) {
let manager = PHImageManager.default()
let option = PHImageRequestOptions()
option.isSynchronous = true
var array: [UIImage] = []
let group = DispatchGroup()
for asset in assets {
group.enter()
manager.requestImage(for: asset, targetSize: CGSize(width: 100.0, height: 100.0), contentMode: .aspectFit, options: option, resultHandler: {(result, info)->Void in
if let thumbnail = result {
array.append(thumbnail)
}
group.leave()
})
}
group.notify(queue: .main) {
completion(array)
}
}
Alamofire上传:
func requestCreateProduct(username:String, product:ProductInfo,images: [UIImage]) {
let url = BASE_URL + "requestCreateProduct"
let parameters: Parameters = [
"username": username,
"productName": product.name,
]
Alamofire.upload(multipartFormData: { multipartFormData in
for (key, value) in parameters {
multipartFormData.append("\(value)".data(using: String.Encoding.utf8)!, withName: key as String)
print("\(key) - \(value)")
}
var count = 1;
for image in images {
multipartFormData.append(UIImageJPEGRepresentation(image, 1.0)!, withName: "files", fileName: String(count) + ".jpg", mimeType: "image/jpg")
count = count + 1
}
}, to:url) { (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
print("Upload Progress: \(progress.fractionCompleted)")
self.delegate?.updateProgressBar(value: Float(progress.fractionCompleted))
})
upload.responseJSON { response in
print(response)
}
case .failure(let encodingError):
debugPrint(encodingError)
}
}
}