ios - 对这种响应长时间运行的异步网络调用的 iOS 方法有任何顾虑吗?

标签 ios swift asynchronous ios8

我编写了一个休眠 6 秒(故意)的 PHP 函数来模拟我的服务器需要很长时间才能响应我的 Swift 应用程序。我想在 Swift 中优雅地处理这个问题,这就是我想到的。对此有任何想法或担忧吗?可以改进吗?

该函数连接到我编写的名为 ContentWebService 的服务 - 这会向服务器发送一个异步帖子,然后做出相应的响应。当你点击按钮时,我禁用它并让它说“正在加载”(这是一个概念证明,我稍后会使用本地化字符串)但基本上我想阻止用户再次点击它(不禁用它,我是能够发出十几个我认为不太好的请求)。

当脚本休眠/响应返回时,您可以浏览应用程序的其余部分并执行您的操作,但无论您身在何处,消息最终都会返回并表明它已成功。

看起来不错??

@IBAction func btnSlow(sender: UIButton) {

    sender.enabled = false //sender is the button - set disabled as it gets clicked
    sender.setTitle("Loading, please wait..", forState: UIControlState.Normal)

    ContentWebService.SlowFunction()
        { (r) -> () in

            if (r.Status == ResponseCode.SUCCESS) {
                dispatch_async(dispatch_get_main_queue()) {
                    self.presentViewController(AlertCreator.ShowSimplePopup("Done", message: "Completed successfully.."), animated: true, completion: nil)
                    sender.enabled = true //reset back to enabled
                    sender.setTitle("Click for Slow Function", forState: UIControlState.Normal) //restore original text
                }
            }
            else {
                dispatch_async(dispatch_get_main_queue()) {
                    self.presentViewController(AlertCreator.ShowSimplePopup(StringHelper.GetLocalizedString("UnknownError"), message: StringHelper.GetLocalizedString("UnknownErrorMessage")), animated: true, completion: nil)
                    sender.enabled = true //reset back to enabled
                    sender.setTitle("Click for Slow Function", forState: UIControlState.Normal) //restore original text
                }
            }
    }

最佳答案

是的,您在该代码中所做的是标准的异步回调过程。我唯一的建议是,如果您还没有超时保证,您应该考虑某种超时保证。

(请注意,如果需要,阻止用户导航到任何地方可能是合理的。您可以在调用 ContentWebService.SlowFunction 之前关闭界面对点击的响应,然后重新打开它当你在匿名完成函数中被回调时。)

关于ios - 对这种响应长时间运行的异步网络调用的 iOS 方法有任何顾虑吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27888493/

相关文章:

java - Akka actor 的 Bulkheading 策略

ios - Parse.com PFLoginView UITextfield 显示问题。不能删除边框?

ios - 将多个值传递给 nextview Controller

ios - Swift CollectionView 自定义布局单元格间距

swift: prepareForSegue indexPathForSelectedRow

ios - 我如何在 swift ios 的导航栏标题中使用图像

android - 自动从 Android 和 IOS 发送短信

ios - 如何在核心数据中应用 group by 子句

c++ - 为什么首选异步IO

angularjs - 无法多次调用 $http.get()