如何在swift iOS中调用for循环中的N个API,在后台调用upadate数组。对于某些循环vales api未被调用

时间:2016-07-11 07:24:05

标签: ios swift nsoperationqueue

我需要的是:

  1. 从一个api我得到我必须检索的总页数。
  2. 然后,在for循环中,我通过进行API调用来检索每个页面。 例如api / page / 0,api / page / 2 ... api / page / n
  3. 我将检索到的数据添加到全局数组
  4. 但是,它没有按照我想要的方式工作

    func callOne(strCat:String,strCount:String) {
        let strURL = strCat + strCount
    
        let url = NSURL(string: strURL)
        let session = NSURLSession.sharedSession()
    
        let task = session.dataTaskWithURL(url!) { data, response, error in
            if data != nil {
                do {
    
                    let arr:NSMutableArray = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSMutableArray
    
                    if arr.count > 0{
                        let dict = arr[0]
                        self.totalPageCount = Int(dict.objectForKey("total_pages") as! Int)
    
                       let queue = NSOperationQueue()
    
                        for (var i = 0 ; i < self.totalPageCount; i++)
                        {
                            let blockOperation = NSBlockOperation{
                                self.callNewsApi(String(self.totalPageCount),strCat: strCat, strCount: String(i), complition: { (finished) -> () in
    
                                    dispatch_async(dispatch_get_main_queue() , { () -> Void in
                                        self.collectionView .reloadData()
                                    })
                                })
                            }
                            queue.addOperation(blockOperation)
                        }
                    }
                } catch {
                }
    
            }
        }
        task.resume()
     }
    
     //MARK: Func second
     func callNewsApi(totalCount:String,strCat:String,strCount:String, complition:(finished:Bool)->())
     {
    
         // EZLoadingActivity.show("Fetching News...", disableUI: false)
         let fullURL = strCat + strCount
         let url = NSURL(string: fullURL)
         let session = NSURLSession.sharedSession()
         let task = session.dataTaskWithURL(url!) { data, response, error in
             if data != nil {
                EZLoadingActivity.hide()
                do {
                    let arr:NSMutableArray = try NSJSONSerialization.JSONObjectWithData(data!, options:NSJSONReadingOptions.MutableContainers ) as! NSMutableArray
    
                    if arr.count > 0{
                        self.arrNews.addObjectsFromArray(arr as NSMutableArray as [AnyObject])
                            self.saveAllNews(fullURL, dict: self.arrNews)
                            complition(finished: true)
                    }
    
                } catch {
    
    
                }
            }
        }
        task.resume()
    
    }
    

    由于

0 个答案:

没有答案