【问题标题】:swift UIActivityIndicatorView while NSURLConnectionNSURLConnection 时快速 UIActivityIndicatorView
【发布时间】:2014-12-21 17:38:34
【问题描述】:
我知道如何为 UIActivityIndicatorView 设置动画
我知道如何与NSURLConnection.sendSynchronousRequest建立联系
但我不知道如何在与NSURLConnection.sendSynchronousRequest 建立连接时为 UIActivityIndicatorView 设置动画
谢谢
【问题讨论】:
标签:
ios
swift
nsurlconnection
uiactivityindicatorview
【解决方案1】:
不要在主线程中使用sendSynchronousRequest(因为它会阻塞你运行它的任何线程)。您可以使用sendAsynchronousRequest,或者,鉴于NSURLConnection 已被弃用,您应该真正使用NSURLSession,然后您尝试使用UIActivityIndicatorView 应该可以正常工作。
例如,在 Swift 3 中:
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .gray)
indicator.center = view.center
view.addSubview(indicator)
indicator.startAnimating()
URLSession.shared.dataTask(with: request) { data, response, error in
defer {
DispatchQueue.main.async {
indicator.stopAnimating()
}
}
// use `data`, `response`, and `error` here
}
// but not here, because the above runs asynchronously
或者,在 Swift 2 中:
let indicator = UIActivityIndicatorView(activityIndicatorStyle: .Gray)
indicator.center = view.center
view.addSubview(indicator)
indicator.startAnimating()
NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error in
defer {
dispatch_async(dispatch_get_main_queue()) {
indicator.stopAnimating()
}
}
// use `data`, `response`, and `error` here
}
// but not here, because the above runs asynchronously
【解决方案2】:
正如@Rob 在评论中指出的那样,只要您使用SynchronousRequest,它就会阻塞您的 UI 线程并且您将无法为任何东西制作动画。 Chris 很好地解释了this article 中NSURLConnection 的两种模式(虽然对于Objective-C,但你会明白的)。除其他外,他将这两种模式比较为
异步还是同步?
那么,您应该为您的应用程序执行异步请求还是使用同步请求?我发现在大多数情况下,我都在使用异步请求,因为否则 UI 会在同步请求执行其操作时被冻结,当用户执行手势或触摸并且屏幕无响应时,这是一个大问题.除非我发出一个请求来做一些非常简单和快速的事情,比如 ping 服务器,否则我默认使用异步模式。
这比我说的更能概括你的选择。因此,您确实应该了解异步变体,以便能够制作动画。