我正在将项目迁移到Swift 5(从Alamofire
4.7.3迁移到5.0.0-beta.5),我遇到的错误是我项目中的uploadImage
函数。 / p>
以前,upload(multipartFormData...)
中的Alamofire
具有参数encodingCompletion: ((SessionManager.MultipartFormDataEncodingResult) -> Void)?)
。在新版本中,这已更改,并且函数返回UploadRequest
。
此外,Alamofire现在支持responseDecodable
内置的Decodable,因此该任务不再需要自定义方法responseDecodeableObject
。
不幸的是,我对Alamofire(通常是网络)缺乏经验,并且不确定是否已经考虑了所有需要考虑的内容。可能会有更多经验的人查看此迁移吗?
旧代码:
static func uploadImage(withImage image: UIImage, completion: @escaping (Member?, Error?) -> Void) {
let putRequest = RequestRouter.saveProfileImage
if let imageData = image.pngRepresentation {
if let url = URL.init(string: putRequest.urlData.path) {
MyNetwork.client.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: "Image", fileName: "Image.png", mimeType: "image/jpeg")
}, to: url,
method: .put,
encodingCompletion: { encodingResult in
switch encodingResult {
case .success(let upload, _, _):
upload.responseDecodableObject(completionHandler: { (response: DataResponse<Member>) in
switch response.result {
case .success(let data):
data.saveInCoreData(completion: { (error) in //save in core data
if let error = error { completion(nil, error); return }
completion(Member.member(withId: data.id), error) //return profile from core data
})
case .failure(let error):
MPage.checkExpiredSession(returnedObject: nil, error: error) { _, _ in
completion(nil, error)
}
}
})
case .failure(let encodingError):
print(encodingError)
completion(nil, encodingError)
}
})
}
} else {
completion(nil, nil)
}
}
新代码:
static func uploadImage(withImage image: UIImage, completion: @escaping (Member?, Error?) -> Void) {
let putRequest = RequestRouter.saveProfileImage
if let imageData = image.pngRepresentation {
if let url = URL.init(string: putRequest.urlData.path) {
let uploadRequest = MyNetwork.client.upload(multipartFormData: { multipartFormData in
multipartFormData.append(imageData, withName: "Image", fileName: "Image.png", mimeType: "image/jpeg")
}, to: url,
method: .put).responseDecodable(completionHandler: { (response: DataResponse<Member>) in
switch response.result {
case .success(let data):
data.saveInCoreData(completion: { (error) in //save in core data
if let error = error { completion(nil, error); return }
completion(Member.member(withId: data.id), error) //return profile from core data
})
case .failure(let error):
MPage.checkExpiredSession(returnedObject: nil, error: error) { _, _ in
completion(nil, error)
}
}
})
}
} else {
completion(nil, nil)
}
}