问题描述
- ios如何等待异步函数执行完成
-
iOS中如何等待异步函数执行完成之后再进行之后的操作
func getMovies()
{
let movieId:NSMutableArray = NSMutableArray()let path = "http://v.juhe.cn/movie/movies.today"; let api_id = "42"; let method = "GET"; let param = ["cityid":7,"key":"c086aa6fd871c407219dc969620be8f7", "dtype":"json"]; let juhepai = JHAPISDK.shareJHAPISDK(); let group = dispatch_group_create() dispatch_group_async(group, dispatch_get_main_queue()) { juhepai.executeWorkWithAPI(path, APIID: api_id, parameters: param, method: method, success:{responseObject in /*成功代码*/ let result = responseObject["result"] as! NSArray for i in 0...result.count-1{ let test:NSString = result[i]["movieId"] as! NSString print(test) movieId.addObject(test) } }, failure:{error in /*失败代码*/ print("dsffadf") } ) } dispatch_group_notify(group, dispatch_get_main_queue()) { } } executeWorkWithAPI是聚合数据提供的异步函数,希望在executeWorkWithAPI的回调函数执行完成之后再print(movieId) 试过用diapatch_group,然而每次都是先执行print(movieId)在执行executeWorkWithAPI的回调函数
解决方案
用信号量来同步。先wait,在异步函数的成功,失败handler中设置信号。这样就可以把异步转成同步
时间: 2024-10-30 01:39:22