xcode 在 api 调用 Swift 上显示活动指示器

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/45409015/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 10:10:07  来源:igfitidea点击:

Display activity indicator on api call Swift

iosswiftxcodeswift3

提问by AJ Sanjay

I want to display an activity indicator when api call is performed. The activity indicator should stop when the api response is received

我想在执行 api 调用时显示一个活动指示器。收到 api 响应时,活动指示器应停止

But Activity indicator is not displaying during the api call am new to swift here is my code.

但是在 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
}
}

This above code is not displaying activity indicator I tried changing the view background colour. and activity indicator colour but no use

上面的代码没有显示活动指示器我尝试更改视图背景颜色。和活动指示器颜色但没有用

采纳答案by Anbu.Karthik

remove your code from

删除您的代码

task.resume()
}

// activityIndicatorView.stopAnimating()
// VW_overlay.isHidden = true

and add into inside the block call your code in the following place

并添加到块内,在以下位置调用您的代码

 let task = URLSession.shared.dataTask(with: request as URLRequest) {
        data, response, error in

       // call here 
       activityIndicatorView.stopAnimating()
        VW_overlay.isHidden = true


        if error != nil {
            print("\(String(describing: error))")
            return
        }
       ......

回答by Jaydeep

Swift 3.0

斯威夫特 3.0

For That what i just implement two function as below. Hope this also will help you.

为此,我只是实现了以下两个功能。希望这也能帮助你。

 func showLoader(view: UIView) -> UIActivityIndicatorView {

        //Customize as per your need
        let spinner = UIActivityIndicatorView(frame: CGRect(x: 0, y: 0, width: 40, height:40))
        spinner.backgroundColor = UIColor.black.withAlphaComponent(0.7)
        spinner.layer.cornerRadius = 3.0
        spinner.clipsToBounds = true
        spinner.hidesWhenStopped = true
        spinner.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.white;
        spinner.center = view.center
        view.addSubview(spinner)
        spinner.startAnimating()
        UIApplication.shared.beginIgnoringInteractionEvents()

        return spinner
    }

And, For hide Activity Indicator

并且,对于隐藏活动指示器

extension UIActivityIndicatorView {  
     func dismissLoader() {
            self.stopAnimating()
            UIApplication.shared.endIgnoringInteractionEvents()
        } 
 }

And, the UIViewControllerwhere you used Indicator as below.

而且,UIViewController您使用指标的位置如下。

    //Show
    let spinner = showLoader(view: self.view)

    //Hide
    spinner.dismissLoader()

回答by Mohammad Sadiq

In your response handler stop the activity indicator.

在您的响应处理程序中停止活动指示器。

func Places_API() {
activityIndicatorView.stopAnimating()
//Handle response here
}