首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >swift UIActivityIndicatorView while

swift UIActivityIndicatorView while
EN

Stack Overflow用户
提问于 2014-12-21 17:38:34
回答 2查看 7.6K关注 0票数 5

我知道如何激活UIActivityIndicatorView,我知道如何与NSURLConnection.sendSynchronousRequest建立连接

但我不知道如何在与UIActivityIndicatorView连接的同时激活NSURLConnection.sendSynchronousRequest

谢谢

EN

回答 2

Stack Overflow用户

回答已采纳

发布于 2014-12-21 18:30:35

不要从主线程中使用sendSynchronousRequest (因为它会阻塞运行它的任何线程)。您可以使用sendAsynchronousRequest,或者,考虑到NSURLConnection不受欢迎,您应该真正使用NSURLSession,然后尝试使用UIActivityIndicatorView应该会很好。

例如,在Swift 3中:

代码语言:javascript
复制
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中:

代码语言:javascript
复制
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
票数 13
EN

Stack Overflow用户

发布于 2014-12-21 18:30:53

正如@Rob在评论中指出的那样,只要您使用SynchronousRequest,它就会阻塞您的UI线程,您将无法动画任何东西。Chris在这篇文章中很好地解释了这篇文章的两种模式(虽然是针对Objective的,但你会明白的)。除其他外,他将这两种模式作了比较

异步还是同步? 因此,您应该执行异步请求还是为应用程序使用同步请求?我发现,在大多数情况下,我使用异步请求,因为否则在同步请求执行时UI将被冻结,当用户执行手势或触摸时,这是一个很大的问题,而屏幕没有响应。除非我启动一个请求来执行一些非常简单和快速的事情,比如ping服务器,否则我默认使用异步模式。

这比我能说的更好地概括了你的选择。因此,您确实应该了解异步变体,以便能够执行您的动画。

票数 1
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27591986

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档