2016-05-05 21 views
0

我有一個集合視圖。我從API中獲取一些數據,並在收藏視圖中顯示它。每件事情都很好。但是當我加載我的屏幕時 - 首先顯示我的屏幕,並且僅在5到6秒的延遲之後才填充數據在我的收藏視圖中。爲了解決這個問題,我做了一些dispatch main thread來快速獲取數據。如何顯示活動指標直到數據獲取並顯示在我的收藏視圖中

但有些時候基於用戶電話的數據連接,數據顯示延遲。例如,如果用戶的數據連接速度較慢,則需要約30秒(假設)才能在我的收藏視圖中顯示數據。

所以,我需要的是 - 如何顯示活動指標 - 直到我的數據顯示在我的收藏視圖中。 我知道如何創建一個虛擬​​並顯示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

我做了一些改變你的代碼和下面是

使用這些作爲類變量

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) 
+0

我需要將活動指示器顏色顯示爲紅色,並將背景視圖顯示爲白色。 – user5513630

+0

在你的代碼中,我試圖改變,但它不會改變。如何改變顏色爲 – user5513630

+0

兩種顏色?你什麼意思? – iOSMAn

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() 
} 

創建Stop方法:

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

然後在您的viewDidLoad中調用startIndicator,上述ListBusinessType方法。 然後當你從api獲得成功和失敗響應時停止它。 這會幫助你。 :)

注:根據您的應用程序主題更改顏色。

+0

感謝您的solution.But我不知道我應該停止。我的意思是在我的API方法。所以只有我張貼我的網絡服務單元格的方法。可以請告訴我在哪裏我應該停止指示器在我的代碼 – user5513630

+0

好吧,寫停止方法上面印刷(錯誤),讓成功= json [ 「成功」]爲? Int –

+0

你有沒有?說如果你還沒有得到? –

相關問題