I apologize in advance for the very long post but I have both a question and potential solution. As many people have pointed out Alamofire has released 5.1.0. The syntax has changed and while I am not 100 % sure I followed it correctly I would like to share what I have. What I would like to know is, is there any better way of doing this and is there any way to incorporate .uploadProgress portion in the success case so the upload percentage can update as the percent climbs. It just shows that it is done and doesn't actually display a progress at the moment.
Thank you for your time Brian and below is the code:
@objc fileprivate func handlePost() {
let url = "http://localhost:1337/post"
let headers: HTTPHeaders = ["Content-type": "multipart/form-data", "Accept": "application/json"]
let hud = JGProgressHUD(style: .dark)
hud.indicatorView = JGProgressHUDRingIndicatorView()
hud.textLabel.text = "Uploading"
hud.show(in: view)
guard let text = postBodyTextView.text else { return }
AF.upload(multipartFormData: { (formData) in
// Post Text
formData.append(Data(text.utf8), withName: "postBody")
// Post Image
guard let imageData = self.selectedImage.jpegData(compressionQuality: 0.5) else { return }
formData.append(imageData, withName: "imagefile", fileName: "Doesn'tMatterSoMuch", mimeType: "image/jpg")
}, to: url,
method: .post,
headers: headers) .uploadProgress(queue: .main, closure: { progress in
print("Upload Progress: \(progress.fractionCompleted)")
DispatchQueue.main.async {
hud.progress = Float(progress.fractionCompleted)
hud.textLabel.text = "Uploading\n\(Int(progress.fractionCompleted * 100))% Complete"
}
}).responseJSON(completionHandler: { data in
}).response { (dataResp) in
switch dataResp.result {
case .success(let result):
hud.dismiss()
if let err = dataResp.error {
print("Failed to hit server:", err)
return
}
if let code = dataResp.response?.statusCode, code >= 300 {
print("Failed to upload with status: ", code)
return
}
print("Successfully created post, here is the response:")
self.dismiss(animated: true) {
self.homeController?.fetchPosts()
}
case .failure(let err):
print("upload err: \(err)")
}
}
}