如何显示 activity 指标直到数据获取并显示在我的 collection 视图中

How to show activity indicator till data fetch and display in my collection view

我有一个 collection 观点。我正在从 API 中获取一些数据并显示它,在我的 collection view.Every 中工作 fine.But 当我加载我的屏幕时 - 首先显示我的屏幕并且仅延迟 5 到 6 秒后,数据将填充到我的 collection 视图中。为了解决这个问题,我做了一些 dispatch main thread 来快速获取数据。

但有时根据用户 phone 的数据连接,数据会延迟显示。例如,如果用户的数据连接速度较慢,则需要大约 30 秒(假设)才能显示数据我的 collection 观点。

所以,我需要的是 - 如何显示 activity 指标 - 直到我的数据显示在我的 collection 视图中。 我知道如何创建虚拟 Activity Indicator 并显示 1 到 30 seconds.But 我必须动态地执行此操作。

这意味着,我需要显示 activity 指标,直到数据显示在我的 collection 视图中。它不应该依赖于用户的数据连接速度。

如何实现?

这是我的代码:

 var BTdata = [BTData]()
 override func viewDidLoad()
    {
        super.viewDidLoad()

 ListBusinessTypes()

}
// Values from Api for Business Types
    func ListBusinessTypes()
    {
        let token = NSUserDefaults.standardUserDefaults().valueForKey("access_token") as! String

        let headers = ["x-access-token": token]

        let request = NSMutableURLRequest(URL: NSURL(string: “some url“)!,
                                          cachePolicy: .UseProtocolCachePolicy,
                                          timeoutInterval: 10.0)
        request.HTTPMethod = "GET"
        request.allHTTPHeaderFields = headers

        let session = NSURLSession.sharedSession()
        let dataTask = session.dataTaskWithRequest(request, completionHandler: { (data, response, error) -> Void in
            if (error != nil)
            {
                print(error)

                let ErrorAlert = UIAlertController(title: "Error", message: "Problem with internet connectivity or server, please try after some time", preferredStyle: UIAlertControllerStyle.Alert)

                // add an action (button)
                ErrorAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                // show the alert
                self.presentViewController(ErrorAlert, animated: true, completion: nil)
            }
            else
            {
                if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? Dictionary<String,AnyObject>
                {
                    let success = json["success"] as? Int

                    if(success == 1)
                    {

                        if let typeValues = json["data"] as? [NSDictionary]
                        {
                            dispatch_async(dispatch_get_main_queue(),{

                                for item in typeValues
                                {
                                    self.BTdata.append(BTData(json:item))
                                }

                                self.collectionView1!.reloadData()
                            })
                        }
                    }
                    else
                    {
                        let message = json["message"] as? String

                        let ServerAlert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)

                        // add an action (button)
                        ServerAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))

                        // show the alert
                        self.presentViewController(ServerAlert, animated: true, completion: nil)
                    }
                }
            }
        })

        dataTask.resume()
    }

要设置指标,请创建 2 个启动和停止指标的方法。如下所示,

先创建IBOutlet

var activityIndicator:UIActivityIndicatorView = UIActivityIndicatorView()

创建启动方法:

 func startIndicator()
{
    //creating view to background while displaying indicator
    let container: UIView = UIView()
    container.frame = self.view.frame
    container.center = self.view.center
    container.backgroundColor = CONTAINER_VIEW_BACKGROUND_COLOR

    //creating view to display lable and indicator
    let loadingView: UIView = UIView()
    loadingView.frame = CGRectMake(0, 0, 118, 80)
    loadingView.center = self.view.center
    loadingView.backgroundColor =  LOADING_VIEW_BACKGROUND_COLOR
    loadingView.clipsToBounds = true
    loadingView.layer.cornerRadius = 10

    //Preparing activity indicator to load
    self.activityIndicator = UIActivityIndicatorView()
    self.activityIndicator.frame = CGRectMake(40, 12, 40, 40)
    self.activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
    loadingView.addSubview(activityIndicator)

    //creating label to display message
    let label = UILabel(frame: CGRectMake(5, 55,120,20))
    label.text = "Loading..."
    label.textColor = UIColor.whiteColor()
    label.bounds = CGRectMake(0, 0, loadingView.frame.size.width / 2, loadingView.frame.size.height / 2)
    label.font = UIFont.systemFontOfSize(12)
    loadingView.addSubview(label)
    container.addSubview(loadingView)
    self.view.addSubview(container)

    self.activityIndicator.startAnimating()
}

创建停止方法:

func stopIndicator()
{
        UIApplication.sharedApplication().endIgnoringInteractionEvents()
        self.activityIndicator.stopAnimating()
        ((self.activityIndicator.superview as UIView!).superview as UIView!).removeFromSuperview()
}

然后在 ListBusinessType 方法上方的 viewdidload 中调用 startIndicator。 然后当你从 api 获得成功和失败响应时停止它。 这会帮助你。 :)

注意:根据您的应用主题更改颜色。

我对你的代码做了一些修改,下面是

将这些用作 class 变量

var actView: UIView = UIView()
var loadingView: UIView = UIView()
var activityIndicator: UIActivityIndicatorView = UIActivityIndicatorView()
var titleLabel: UILabel = UILabel()

并且在你的服务调用函数中

showActivity(self.view, myTitle: "Loading...")
let dataTask = session.dataTaskWithRequest(request) {(data, response, error)  in
    dispatch_async(dispatch_get_main_queue(), {
        if response != nil {
            if error != nil {
                print(error)
                removeActivity(self.view)
                let ErrorAlert = UIAlertController(title: "Error", message: "Problem with internet connectivity or server, please try after some time", preferredStyle: UIAlertControllerStyle.Alert)
                // add an action (button)
                ErrorAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
                // show the alert
                self.presentViewController(ErrorAlert, animated: true, completion: nil)
            }else {
                if let json = (try? NSJSONSerialization.JSONObjectWithData(data!, options: [])) as? Dictionary<String,AnyObject> {
                    let success = json["success"] as? Int
                    if(success == 1) {
                        if let typeValues = json["data"] as? [NSDictionary] {
                            dispatch_async(dispatch_get_main_queue(),{
                                for item in typeValues {
                                    self.BTdata.append(BTData(json:item))
                                }
                                self.collectionView1!.reloadData()

                                removeActivity(self.view)
                            })
                        } else {
                            removeActivity(self.view)
                        }
                    } else {

                        removeActivity(self.view)

                        let message = json["message"] as? String
                        let ServerAlert = UIAlertController(title: "Error", message: message, preferredStyle: UIAlertControllerStyle.Alert)
                        // add an action (button)
                        ServerAlert.addAction(UIAlertAction(title: "OK", style: UIAlertActionStyle.Default, handler: nil))
                        // show the alert
                        self.presentViewController(ServerAlert, animated: true, completion: nil)
                    }
                } else {

                    removeActivity(self.view)
                }
            }
        }
        })

    }

dataTask.resume()

开始动画的函数

  func showActivity(myView: UIView, myTitle: String) {
    myView.userInteractionEnabled = false
    myView.window?.userInteractionEnabled = false
    myView.endEditing(true)
    actView.frame = CGRectMake(0, 0, myView.frame.width, myView.frame.height)
    actView.center = myView.center
    actView.backgroundColor = UIColor(red: 0, green: 0, blue: 0, alpha: 0.3)

    loadingView.frame = CGRectMake(0, 0, 80, 80)
    loadingView.center = myView.center
    loadingView.backgroundColor = THEME_COLOUR
    loadingView.clipsToBounds = true
    loadingView.layer.cornerRadius = 15

    activityIndicator.frame = CGRectMake(0.0, 0.0, 40.0, 40.0);
    activityIndicator.activityIndicatorViewStyle = UIActivityIndicatorViewStyle.WhiteLarge
    activityIndicator.center = CGPointMake(loadingView.frame.size.width / 2, loadingView.frame.size.height / 2);

    titleLabel.frame = CGRectMake(5, loadingView.frame.height-20, loadingView.frame.width-10, 20)
    titleLabel.textColor = UIColor.whiteColor()
    titleLabel.adjustsFontSizeToFitWidth = true
    titleLabel.textAlignment = NSTextAlignment.Center
    titleLabel.text = myTitle
    titleLabel.font = IH_DELEGATE.BoldAppFontOfSize(10)

    loadingView.addSubview(activityIndicator)
    actView.addSubview(loadingView)
    loadingView.addSubview(titleLabel)
    myView.addSubview(actView)
    activityIndicator.startAnimating()
}

停止动画的函数

func removeActivity(myView: UIView) {
    myView.userInteractionEnabled = true
    myView.window?.userInteractionEnabled = true
    activityIndicator.stopAnimating()
    actView.removeFromSuperview()
}

编辑 忘了说

let THEME_COLOUR = UIColor (red:0.188, green:0.682, blue:0.886, alpha:1)