gpt4 book ai didi

ios - 无法弄清楚如何管理 MBProgressHUD 和调度

转载 作者:行者123 更新时间:2023-11-30 12:19:50 24 4
gpt4 key购买 nike

我正在实现一个 iOS 应用程序,并尝试在将照片上传到服务器时执行以下操作:

  • 使用 Alamofire 开始上传过程
  • 使用 MBProgressHUD 显示进度指示器
  • 上传完成后,隐藏进度指示器
  • 根据服务器响应,显示一条消息(成功或失败)然后关闭 View

我无法实现这一点,尤其是在显示响应消息 2 秒后关闭 View 。这是我的代码。请问您将如何进行?谢谢。

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)
})
}
}
}
}

最佳答案

我找到了一个效果很好的解决方案。最后一个 DispatchQueue 会关闭 View ,但不会在 2 秒后立即执行。这是代码:

DispatchQueue.main.asyncAfter(deadline: .now() + 1) {
self.extensionContext?.completeRequest(returningItems: nil, completionHandler: nil)
}

希望对您有所帮助。

关于ios - 无法弄清楚如何管理 MBProgressHUD 和调度,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44930205/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com