我目前正在进行 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()
}
解决您的问题的一个可能的解决方案是使用重复同时使用信号量来等待异步调用。但请注意,尝试在主线程中执行此操作可能会阻塞您的 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)