I'm implementing an iOS app and trying to do the following while uploading a photo to a server:
- Start upload process with Alamofire
- Display a progress indicator with MBProgressHUD
- When the upload is done, hide the progress indicator
- Depending on the server response, display a message (success or fail) then dismiss the view
And I'm not able to achieve that, especially about dismissing the view after displaying the response message for 2 seconds. Here is my code. How would you proceed please? Thanks.
class ShareViewController: UIViewController {
var progressHUD: MBProgressHUD! = nil
func sendToServer(image: UIImage, imageName: String) {
Alamofire.upload(multipartFormData: { multipartFormData in
multipartFormData.append(jpgImageData!, withName: "photos",fileName: fname, mimeType: mime)
for (key, value) in parameters {
multipartFormData.append(value.data(using: String.Encoding.utf8)!, withName: key)
}
},
to:url!)
{ (result) in
switch result {
case .success(let upload, _, _):
upload.uploadProgress(closure: { (progress) in
DispatchQueue.main.async(execute: {
self.progressHUD.show(animated: true)
self.progressHUD.progress = (Float(progress.fractionCompleted))
self.progressHUD.hide(animated: true, afterDelay: 3)
})
})
upload.responseJSON { response in
if response.response?.statusCode == 200{
if let result = response.result.value {
var message = String()
message = "200, OK"
self.progressHUD.label.text = message
self.progressHUD.show(animated: true)
self.progressHUD.hide(animated: true, afterDelay: 2)
DispatchQueue.main.async(execute: {
self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
})
}
}
else{
var message = String()
message = "Not 200, NOK"
self.progressHUD.label.text = message
self.progressHUD.show(animated: true)
self.progressHUD.hide(animated: true, afterDelay: 2)
DispatchQueue.main.async(execute: {
self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
})
}
}
case .failure(let encodingError):
print(encodingError)
var message = String()
message = "Failure, NOK"
self.progressHUD.label.text = message
self.progressHUD.show(animated: true)
self.progressHUD.hide(animated: true, afterDelay: 2)
DispatchQueue.main.async(execute: {
self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
})
}
}
}
}