dam*_*net 5 nsurlconnection uiactivityindicatorview ios swift
我知道如何动画UIActivityIndicatorView我知道如何建立连接 NSURLConnection.sendSynchronousRequest
但我不知道如何动画UIActivityIndicatorView WHILE与之建立联系 NSURLConnection.sendSynchronousRequest
谢谢
Rob*_*Rob 13
不要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
Run Code Online (Sandbox Code Playgroud)
或者,在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
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
6449 次 |
| 最近记录: |