2016-06-20 8 views
1

Ich habe zwei Anfragen. Jeder von ihnen erhält unterschiedliche Daten. Ich muss einen Indikator anzeigen, wenn alle zwei Anfragen anfordern. Wie kann ich das machen? dies ist meine erste Anfrage:Zeige Indikator für zwei Anfrage

func productList(tableView:UITableView,spinner:UIActivityIndicatorView,index1:Int,index2:Int,index3:Int){ 

    if product.count<=0{ 

     alamoFireManager?.request(.GET, "http://mobile.unimax.kz/api/Default1",parameters: ["type1id":index1,"type2id":index2,"type3id":index3,"name":"","userid":1089]) 
      .responseJSON { response in 
       guard response.result.error == nil else { 
        if let httpError = response.result.error { 
         switch(httpError.code){ 
         case -1009: 
          let alert = UIAlertView(title: "Ошибка",message: "Нету интернета!!",delegate: nil,cancelButtonTitle: "OK") 
          alert.show() 
          break 
         default: 
          let alert = UIAlertView(title: "Ошибка",message: "Повторите попытку!!",delegate: nil,cancelButtonTitle: "OK") 
          alert.show() 
          break 
         } 
        } else { //no errors 
         let statusCode = (response.response?.statusCode)! 
         print(statusCode) 
        } 
        spinner.stopAnimating() 
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
        return 

       } 

       if let value = response.result.value { 
        // handle the results as JSON, without a bunch of nested if loops 
        let product = JSON(value) 
        for (_,subJson):(String, JSON) in product { 

         let img:NSData 
         if let src=subJson["sphoto"].string{ 

          if src.containsString("jpg"){ 
           let range = src.startIndex.advancedBy(2)..<src.endIndex 
           let substring = src[range] 
           var urlString = "http://admin.unimax.kz/\(substring)" 
           urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! 
           if let dataFromURL=NSData(contentsOfURL: NSURL(string: urlString)!){ 
            img=dataFromURL 
           } 
           else{ 
            img=NSData(contentsOfURL: NSURL(string: "http://zhaksy-adam.kz/Images/domalak.png")!)! 
           } 
          } 
          else{ 
           img=NSData(contentsOfURL: NSURL(string: "http://zhaksy-adam.kz/Images/domalak.png")!)! 
          } 
         } 
         else{ 
          img=NSData(contentsOfURL: NSURL(string: "http://zhaksy-adam.kz/Images/domalak.png")!)! 
         } 

         //Do something you want 
         let id=subJson["id"].int! 
         let name=subJson["name"].string! 
         let price=subJson["price"].int! 
         let description=subJson["description"].rawString() 
         self.product.append(Product(id:id,title: name, img: UIImage(data: img), price: price,desc:description!)) 
        } 
        spinner.stopAnimating() 
        UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
        tableView.reloadData() 
       } 
     } 
    } 
    else{ 
     spinner.stopAnimating() 
     UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
     tableView.reloadData() 
    } 
} 

und dies ist meine zweite Anfrage:

func makeGetFav(userID:Int,completionHandler: (responseObject:JSON) ->()) { 
    alamoFireManager?.request(.GET, "http://mobile.unimax.kz/api/Klientapi/?authid=\(userID)") 
     .responseJSON {response in 
      guard response.result.error == nil else { 
       if let httpError = response.result.error { 
        switch(httpError.code){ 
        case -1009: 
         let alert = UIAlertView(title: "Ошибка",message: "Нету интернета!!",delegate: nil,cancelButtonTitle: "OK") 
         alert.show() 
         break 
        default: 
         let alert = UIAlertView(title: "Ошибка",message: "Повторите попытку!!",delegate: nil,cancelButtonTitle: "OK") 
         alert.show() 
         break 
        } 
       } else { //no errors 
        let statusCode = (response.response?.statusCode)! 
        print(statusCode) 
       } 
       return 
      } 
      completionHandler(responseObject: JSON(response.result.value!)) 
    } 
} 

func getFavs(userID:Int,tableView:UITableView,spinner:UIActivityIndicatorView){ 
    getFavRequets(userID){(responseObject) in 
     if responseObject != nil{ 
      self.favs.removeAll() 
      self.localDB.clearFav() 
      for (_,subJson):(String, JSON) in responseObject { 
       self.favs.append(FavModel(id: subJson["id"].int!, title: subJson["name"].string!, price: subJson["price"].int!)) 
      } 
      spinner.stopAnimating() 
      UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
      tableView.reloadData() 

     } 
    } 
} 

gibt es nenne ich alles:

UIApplication.sharedApplication().networkActivityIndicatorVisible = true 
    indicator.startAnimating() 

    localDB.getUserInfo() 
    getRequests.productList(tableView, spinner: indicator, index1: catalog1Index, index2: catalog2Index, index3: catalog3Index) 
    if localDB.user.count>0{ 
     getRequests.getFavs(localDB.user[0].id, tableView: tableView, spinner: indicator) 
    } 
    localDB.checkCart(tableView, tabCtrl: tabBarController!) 

Antwort

0

Eine sehr schnelle Art und Weise, es zu tun:

// global var 

var isIndicatorActive : Bool = false 


UIApplication.sharedApplication().networkActivityIndicatorVisible = true 
    indicator.startAnimating() 
    self.isIndicatorActive = true 

In der Zeile vor jedem alamoFireManager?.request Sie rufen:

if isIndicatorActive == false { 
    UIApplication.sharedApplication().networkActivityIndicatorVisible = true 
     indicator.startAnimating() 
     self.isIndicatorActive = true 
} 

nach jeder Zeile spinner.stopAnimating() und fügen:

self.isIndicatorActive = false 
0

ich Ihnen vorschlagen, einen Zähler einzigen Netzwerk-Aktivitätsanzeige zu verwenden und halten, die den Überblick über die Netzwerkaktivität halten innerhalb der Anwendung. Ich weiß, dass meine Antwort mehr im Text ist, aber wenn ich deinen Code betrachte, scheint es, dass du Folgendes implementieren kannst.

0 zeigt keinen Aktivitätsindikator an.

Sobald eine neue Aktivität beginnt, erhöhen Sie den Zähler, überprüfen Sie, ob der Zähler größer als 0 ist, und zeigen Sie das Kennzeichen an.

Verringern Sie den Zähler, wenn die Aktivitätsaufgabe abgeschlossen ist. Beim Dekrementieren überprüfen Sie, ob der Zähler 0 ist, und setzen Sie die Sichtbarkeit des Indikators auf false.

PS: Vergessen Sie nicht, die Sync-Blöcke zu inkrementieren/dekrementieren. Sie können dafür die Methoden objc_sync_enter (..) und objc_sync_exit (..) verwenden.

Thx

0

Sie können es steuern, um einen Singleton mit ihm zu starten und stoppen nach der Anzahl der laufenden Anfragen:

class NetworkActivityIndicator: NSObject { 

    static let sharedInstance = NetworkActivityIndicator() 

    private override init() { 
    } 

    var count = 0 { 
     didSet { 
      self.updateIndicator() 
     } 
    } 

    private func updateIndicator() { 
     if count > 0 { 
      UIApplication.sharedApplication().networkActivityIndicatorVisible = true 
     } else { 
      UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
     } 
    } 
} 

Die Sie einfach NetworkActivityIndicator.sharedInstance.count += 1 rufen kurz vor der Anfrage und NetworkActivityIndicator.sharedInstance.count += 1, wenn Sie Erhalten Sie die Antwort

0

Der einfachste Weg besteht darin, zwei Variablen zu Ihrer Klasse hinzuzufügen, die angeben, ob die zugehörige Anfrage abgeschlossen ist, und dann eine Funktion zu erstellen, die t stoppt Er dreht nur, wenn beide Variablen anzeigen, dass die Anrufe abgeschlossen sind.

Wenn Sie die Klasse für mehr als einen ViewController verwenden möchten, empfehle ich, eine struct-enum-Kombination hinzuzufügen, um die Variablen zu organisieren, die angeben, welche Anforderungen gerade ausgeführt werden.

zB

class GetRequests { 

    var productsLoaded = false 
    var favoritesLoaded = false 

    func stopSpinnerIfNeeded(spinner: UIActivityIndicatorView) { 
     if productsLoaded && favoritesLoaded { 
      spinner.stopAnimating() 
      spinner.hidden = true 
     } 
    } 


    func productList(tableView:UITableView,spinner:UIActivityIndicatorView,index1:Int,index2:Int,index3:Int){ 

    defer { 
     productsLoaded = true 
     stopSpinnerIfNeeded(spinner) 
    } 

    if product.count<=0{ 

     alamoFireManager?.request(.GET, "http://mobile.unimax.kz/api/Default1",parameters: ["type1id":index1,"type2id":index2,"type3id":index3,"name":"","userid":1089]) 
     .responseJSON { response in 
      guard response.result.error == nil else { 
       if let httpError = response.result.error { 
        switch(httpError.code){ 
        case -1009: 
         let alert = UIAlertView(title: "Ошибка",message: "Нету интернета!!",delegate: nil,cancelButtonTitle: "OK") 
         alert.show() 
         break 
        default: 
         let alert = UIAlertView(title: "Ошибка",message: "Повторите попытку!!",delegate: nil,cancelButtonTitle: "OK") 
         alert.show() 
         break 
        } 
       } else { //no errors 
        let statusCode = (response.response?.statusCode)! 
        print(statusCode) 
       } 
       UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
       return 

      } 

      if let value = response.result.value { 
       // handle the results as JSON, without a bunch of nested if loops 
       let product = JSON(value) 
       for (_,subJson):(String, JSON) in product { 

        let img:NSData 
        if let src=subJson["sphoto"].string{ 

         if src.containsString("jpg"){ 
          let range = src.startIndex.advancedBy(2)..<src.endIndex 
          let substring = src[range] 
          var urlString = "http://admin.unimax.kz/\(substring)" 
          urlString = urlString.stringByAddingPercentEncodingWithAllowedCharacters(NSCharacterSet.URLQueryAllowedCharacterSet())! 
          if let dataFromURL=NSData(contentsOfURL: NSURL(string: urlString)!){ 
           img=dataFromURL 
          } 
          else{ 
           img=NSData(contentsOfURL: NSURL(string: "http://zhaksy-adam.kz/Images/domalak.png")!)! 
          } 
         } 
         else{ 
          img=NSData(contentsOfURL: NSURL(string: "http://zhaksy-adam.kz/Images/domalak.png")!)! 
         } 
        } 
        else{ 
         img=NSData(contentsOfURL: NSURL(string: "http://zhaksy-adam.kz/Images/domalak.png")!)! 
        } 

        //Do something you want 
        let id=subJson["id"].int! 
        let name=subJson["name"].string! 
        let price=subJson["price"].int! 
        let description=subJson["description"].rawString() 
        self.product.append(Product(id:id,title: name, img: UIImage(data: img), price: price,desc:description!)) 
       } 
       UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
       tableView.reloadData() 
      } 
     } 
    } 
    else{ 

     UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
     tableView.reloadData() 
    } 
} 

    func getFavs(userID:Int,tableView:UITableView,spinner:UIActivityIndicatorView){ 
getFavRequets(userID){(responseObject) in 
     if responseObject != nil{ 
      self.favs.removeAll() 
      self.localDB.clearFav() 
      for (_,subJson):(String, JSON) in responseObject { 
       self.favs.append(FavModel(id: subJson["id"].int!, title: subJson["name"].string!, price: subJson["price"].int!)) 
      } 

      favoritesLoaded = true 
      stopSpinnerIfNeeded(spinner) 
      UIApplication.sharedApplication().networkActivityIndicatorVisible = false 
      tableView.reloadData() 

     } 
    } 
} 
0

bedankt sich bei allen für die Hilfe. Ich löse es so:

func makeReuest1(){ 
    if localDB.user.count>0{ 
     getRequests.getFavs(localDB.user[0].id) 
    } 
    makeRequest2() 
} 

func makeRequest2(){ 
    getRequests.productList(tableView, spinner: indicator, index1: catalog1Index, index2: catalog2Index, index3: catalog3Index) 
} 
Verwandte Themen