我想在执行API调用时显示活动指示器。活动指示器应在收到api响应时停止
但是活动指示器在API调用期间不显示我是swift的新手,这是我的代码。
import UIKit
var ARR_states : NSArray = NSArray()
var activityIndicatorView: UIActivityIndicatorView = UIActivityIndicatorView()
var VW_overlay: UIView = UIView()
class VC_search_Course: UIViewController {
@IBOutlet weak var TBL_states :UITableView!
override func viewDidLoad() {
super.viewDidLoad()
VW_overlay = UIView(frame: UIScreen.main.bounds)
VW_overlay.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.5)
activityIndicatorView = UIActivityIndicatorView(activityIndicatorStyle: .whiteLarge)
activityIndicatorView.frame = CGRect(x: 0, y: 0, width: activityIndicatorView.bounds.size.width, height: activityIndicatorView.bounds.size.height)
activityIndicatorView.center = VW_overlay.center
VW_overlay.addSubview(activityIndicatorView)
VW_overlay.center = view.center
view.addSubview(VW_overlay)
activityIndicatorView.startAnimating()
perform(#selector(self.Places_API), with: activityIndicatorView, afterDelay: 0.01)
}
override func didReceiveMemoryWarning() {
super.didReceiveMemoryWarning()
}
@IBAction func button_back(sender: UIButton) {
self.dismiss(animated: false, completion: nil)
}
func Places_API()
{
let STR_url = String(format: "%@/search_by_location", SERVER_URL)
let auth_tok = String(format:"%@",UserDefaults.standard.value(forKey:"auth_token") as! CVarArg)
if let url = NSURL(string:STR_url) {
let request = NSMutableURLRequest(url: url as URL)
request.httpMethod = "GET"
request.addValue("application/json", forHTTPHeaderField: "Accept")
request.addValue(auth_tok, forHTTPHeaderField: "auth_token")
let task = URLSession.shared.dataTask(with: request as URLRequest) {
data, response, error in
if error != nil {
print("\(String(describing: error))")
return
}
let temp_dictin: [AnyHashable: Any]? = ((try? JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers)) as? [AnyHashable: Any])
ARR_states = temp_dictin?["course_locations"] as! NSArray
NSLog("States response %@", ARR_states)
}
task.resume()
}
activityIndicatorView.stopAnimating()
VW_overlay.isHidden = true
}
}
上面的代码没有显示活动指示器,我试着改变视图背景颜色。和活动指示器颜色,但没有用
4条答案
按热度按时间ffx8fchx1#
雨燕3.0
为此我实现了下面两个函数,希望对你有帮助。
和,用于隐藏活动指示器
并且,您使用指示器的
UIViewController
如下所示。e5nszbig2#
删除代码
并添加到块中,在以下位置调用代码
7ivaypg93#
在响应处理程序中停止活动指示器。
vptzau2j4#
添加加载器类
用法:
结果: