如何显示活动指示器,直到数据提取并显示在我的集合视图中

时间:2016-05-05 05:33:24

标签: ios swift uiactivityindicatorview

我有一个集合视图。我正在从API获取一些数据,我正在我的集合视图中显示它。每件事情都很好。但是当我加载我的屏幕时 - 首先显示我的屏幕,并且仅在延迟5到6秒之后,填充数据在我的收藏视图中。为了解决这个问题,我做了一些dispatch main thread来快速获取数据。

但有时基于用户手机的数据连接,数据显示较晚。例如,如果用户数据连接速度较慢,则需要大约30秒(假设)才能显示数据我的收藏视图。

所以,我需要的是 - 如何显示活动指示器 - 直到我的数据显示在我的集合视图中。 我知道如何创建一个虚拟Activity Indicator并显示1到30秒。但我必须动态地执行此操作。

这意味着,我需要显示活动指示器,直到数据显示在我的集合视图中。它不应该取决于用户的数据连接速度。

如何实现这一目标?

这是我的代码:

 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 个答案:

答案 0 :(得分:2)

我对您的代码进行了一些更改,下面是

将这些用作类变量

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)

答案 1 :(得分:1)

要设置指标,请创建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()
}

然后在viewDidload中调用startIndicator,在ListBusinessType方法之上。 当你从api获得成功和失败回应时停止它。 这会对你有所帮助。 :)

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