【发布时间】:2015-01-11 15:03:34
【问题描述】:
我编写了一个休眠 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
}
}
}
【问题讨论】:
-
你不必说
(r) -> () in。说r in就够了。 - 请不要以大写字母开头的函数名! -
非常感谢马特。欣赏建议。在 Swift 中,函数通常使用驼峰式,但首字母小写?
-
是的,驼色外壳在内部是正常的。有一些 C 函数的名称以大写开头,但一般来说,如果您使用大写的类型(类等
CamelCase)和小写的变量和方法(camelCase)。否则你的代码看起来很奇怪,对我们中的一些人来说可能有点难以阅读。 :)
标签: ios swift asynchronous ios8