0

well, I am just about to turn crazy. I am a swift beginner with quite a big programming action going on and it is getting a bit overwhelming. Maybe you can assist.

func getDataFromDatamanager() {
    DataManager.getGoldPriceFromQuandlWithSuccess { (QuandlGoldPrice) -> Void in
        let json = JSON(data: QuandlGoldPrice)
        if let datasetMineral = json["dataset"]["dataset_code"].string {
            print("NSURLSession: \(datasetMineral)")
        }
    DataManager.getSilverPriceFromQuandlWithSuccess { (QuandlSilverPrice) -> Void in
        let json = JSON(data: QuandlSilverPrice)
        if let datasetMineral = json["dataset"]["dataset_code"].string {
            print("NSURLSession: \(datasetMineral)")
        }
}

There are about 15 other calls in this function and they all need a different time to download. I am calling the function to operate on the main thread and to start an activity Indicator:

dispatch_async(dispatch_get_main_queue(), {
        self.activityIndicator.startAnimating()
        self.getDataFromDatamanager()
    })

My question: How can I stop the activity Indicator only once all functions are downloaded?

4

1 回答 1

1

Introduce completedItems: variable. You can increase that when the download complete for some function. after every completion calls the stop activity function, like this :-

var completedItems:Int = 0

func getDataFromDatamanager() {
DataManager.getGoldPriceFromQuandlWithSuccess { (QuandlGoldPrice) -> Void in
    let json = JSON(data: QuandlGoldPrice)
    if let datasetMineral = json["dataset"]["dataset_code"].string {
        completedItems = completedItems + 1 // completedItems ++
        stopActivity()
        print("NSURLSession: \(datasetMineral)")
    }
DataManager.getSilverPriceFromQuandlWithSuccess { (QuandlSilverPrice) -> Void in
    let json = JSON(data: QuandlSilverPrice)
    if let datasetMineral = json["dataset"]["dataset_code"].string {
        completedItems = completedItems + 1 // completedItems ++
        stopActivity()
        print("NSURLSession: \(datasetMineral)")
    }

}

func stopActivity() {
     if completedItems == 15  { // give # of functions
        dispatch_sync(dispatch_get_main_queue(), {
            self.activityIndicator.stopAnimating()
        })
      }
}
于 2016-03-17T06:30:38.940 回答