我正在进行API调用以返回一堆JSON数据,解析它,然后根据几个不同的标准对其进行排序。在解析了JSON数据之后(它回收了一堆食谱),它通过一些功能进行过滤,这些功能可以调整结果池以更准确地符合用户的要求(即,用户只需要花费不到30分钟准备的食谱)。
有时在所有这些过滤器之后,没有更多食谱了! - 当发生这种情况时,我想再次自动重新调用API。我不确定如何在不创建某种无限循环的情况下执行此操作 - 下面的代码:
SLApiCall.sharedCall.callGetApi(SearchUrl, params: dictPara) { (response, err ) -> () in
var data = response!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var localError: NSError?
var jsonobj: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &localError) as? NSDictionary
var arrTemp : NSArray = (jsonobj?.valueForKey("matches") as? NSArray)!
var totalMatches = jsonobj.valueForKey("totalMatchCount") as! Int
User.currentUser.setTotalRecipesMatched(totalMatches)
let (max, min) = User.currentUser.ingredientsCountBasedOnLazyOption()
printTimeElapsedWhenRunningCode("test12345") {
self.arrRecipes = self.SortingArray(arrTemp.arrayByReplacingNullsWithBlanks(), maxLimit: max, minLimit: min)
// This is where all the sorting happens, if this returns an empty array I want to re-call the method.
}
User.currentUser.setList(self.arrRecipes!, param: theJSONText as! String)
self.assignDemoData()
}
答案 0 :(得分:2)
问题的一个可能解决方案是使用repeat-while使用信号量来等待异步调用。请注意,尽管如此,尝试在主线程中执行此操作可能会阻止您的UI,因此可能希望它在辅助线程/队列中执行。还必须在主线程中更新UI等:
repeat{
dispatch_semaphore_t sem = dispatch_semaphore_create(0);
var gotData = false
SLApiCall.sharedCall.callGetApi(SearchUrl, params: dictPara) { (response, err ) -> () in
var data = response!.dataUsingEncoding(NSUTF8StringEncoding, allowLossyConversion: false)
var localError: NSError?
var jsonobj: NSDictionary! = NSJSONSerialization.JSONObjectWithData(data!, options: NSJSONReadingOptions.MutableContainers, error: &localError) as? NSDictionary
var arrTemp : NSArray = (jsonobj?.valueForKey("matches") as? NSArray)!
var totalMatches = jsonobj.valueForKey("totalMatchCount") as! Int
User.currentUser.setTotalRecipesMatched(totalMatches)
let (max, min) = User.currentUser.ingredientsCountBasedOnLazyOption()
printTimeElapsedWhenRunningCode("test12345") {
self.arrRecipes = self.SortingArray(arrTemp.arrayByReplacingNullsWithBlanks(), maxLimit: max, minLimit: min)
// This is where all the sorting happens, if this returns an empty array I want to re-call the method.
if(self.arrRecipea.count){
gotData = true
}
}
User.currentUser.setList(self.arrRecipes!, param: theJSONText as! String)
self.assignDemoData()
dispatch_semaphore_signal(sem)
}
//Wait until the block is called
dispatch_semaphore_wait(sem, DISPATCH_TIME_FOREVER); //Note- have a meaningful timeout here
}while (gotData != true)