2016-12-08 1 views
1

을 마친 경우에만 반환 내가 항목의 목록을 다음 내가 그들을 구문 분석 Alamofire 호출이 있습니다비동기 호출 in 루프 함수. 비동기가

class func getList(_ completion:@escaping (Array<Item>) -> Void) { 
    Alamofire.request("http://foo.com", method: .get, parameters: nil, headers: nil) 
     .responseJSON { response in 
      let list = parseList(response as! NSArray) 
      completion(list) 
    } 
} 

내가 항목의 상태를 확인하기 위해 다른 통화를해야 목록을 구문 분석 할 때 :

class func parseList(_ responseArray: NSArray) -> Array<Item> { 
    let list = NSMutableArray() 
    for itemDic in responseArray { 
     let item = Item() 
     item.id = itemDic.value(forKey: "Id") as? Int 
     item.name = itemDic.value(forKey: "Name") as? Int 

     Alamofire.request("http://bar.com", method: .get, parameters: nil, headers: nil) 
      .responseJSON { response in 
       item.status = response as? String 
     } 
     list.add(item) 
    } 
    return list as NSArray as! Array<Item> 
} 

주요 문제

첫 번째 FUNC에 완료되기 전에 상태들과 루프가 이미 배열을 반환 할 때 지금은 어떤 상태 응답을 얻을 나는 모든 항목을 가질 필요가 있다는 것입니다. 상태와 구문 분석 된 목록을 반환하는 가장 좋은 솔루션은 무엇입니까?

+0

디스패치 그룹과 dispatch_group_wait를 사용하여 'completjon (list)'을 호출하십시오. – Paulw11

답변

0

구문 분석을 닫고 모든 상태가 설정 될 때까지 DispatchGroup을 추가하십시오.

먼저 FUNC :

class func getList(_ completion:@escaping (Array<Item>) -> Void) { 
    Alamofire.request("http://foo.com", method: .get, parameters: nil, headers: nil) 
     .responseJSON { response in 
      self.parseList(response as! NSArray, completion: { (list) in 
       completion(list) 
      }) 
    } 
} 

둘째 FUNC : 여기에서

class func parseList(_ responseArray: NSArray, completion:@escaping(Array<Item>) - Void) { 
    let dispatch = DispatchGroup() 
    let list  = NSMutableArray() 
    for itemDic in responseArray { 
     let item = Item() 
     item.id = itemDic.value(forKey: "Id") as? Int 
     item.name = itemDic.value(forKey: "Name") as? Int 
     dispatch.enter() 
     Alamofire.request("http://bar.com", method: .get, parameters: nil, headers: nil) 
      .responseJSON { response in 
       item.status = response as? String 
       dispatch.leave() 
     } 
     list.add(item) 
    } 
    dispatchGroup.notify(queue: DispatchQueue.main) { 
     completion(list as NSArray as! Array<Item>) 
    } 
} 
-1
당신은 당신이 원하는 것을 달성하기 위해 간단한 루프 카운터를 사용할 수 있습니다

...

class func getList(_ completion:@escaping (Array<Item>) -> Void) { 
    Alamofire.request("http://foo.com", method: .get, parameters: nil, headers: nil) 
     .responseJSON { response in 
      let list = parseList(response as! NSArray) 
      completion(list) 
    } 
} 

내가 수정 귀하의 코드 중 일부 ... 나는 항목이있는 항목의 전체 목록으로 콜백을 던지는시기를 결정하기 위해 카운터를 선언했습니다.

class func parseList(_ responseArray: NSArray, _ completion: @escaping (Array<Any>) -> Void) { 
    let list = NSMutableArray() 
    let counter: Int = 0 // counter 

    for itemDic in responseArray { 
     let item = Item() 
     item.id = itemDic.value(forKey: "Id") as? Int 
     item.name = itemDic.value(forKey: "Name") as? Int 

     Alamofire.request("http://bar.com", method: .get, parameters: nil, headers: nil) 
      .responseJSON { response in 
       item.status = response as? String 

       list.add(item) // when the alamofire return the call we set the status then add it to our list.. 
       counter += 1 // then increment our counter 

       // here ... we verify if the counter matches the total count of the item we need need to fetch 
       if responseArray.count == counter { 
        completion(list) // if it matches the total count then we will fire the callback with the list of the item with statuses. 
       } 
     } 
    } 
} 
관련 문제