我知道如何激活UIActivityIndicatorView,我知道如何与NSURLConnection.sendSynchronousRequest建立连接
但我不知道如何在与UIActivityIndicatorView连接的同时激活NSURLConnection.sendSynchronousRequest
谢谢
发布于 2014-12-21 18:30:35
不要从主线程中使用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发布于 2014-12-21 18:30:53
正如@Rob在评论中指出的那样,只要您使用SynchronousRequest,它就会阻塞您的UI线程,您将无法动画任何东西。Chris在这篇文章中很好地解释了这篇文章的两种模式(虽然是针对Objective的,但你会明白的)。除其他外,他将这两种模式作了比较
异步还是同步? 因此,您应该执行异步请求还是为应用程序使用同步请求?我发现,在大多数情况下,我使用异步请求,因为否则在同步请求执行时UI将被冻结,当用户执行手势或触摸时,这是一个很大的问题,而屏幕没有响应。除非我启动一个请求来执行一些非常简单和快速的事情,比如ping服务器,否则我默认使用异步模式。
这比我能说的更好地概括了你的选择。因此,您确实应该了解异步变体,以便能够执行您的动画。
https://stackoverflow.com/questions/27591986
复制相似问题