我目前正在调用一个 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()
}
最佳答案
您的问题的一个可能解决方案是使用 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)
关于ios - 解析数据后如何循环API调用Swift,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32042882/