![](/img/trans.png)
[英]How to use DispatchGroup to make asynchronous calls within a for loop
[英]DispatchGroup with Asynchronous function
我使用Alamofire
来获取请求。 我有两个UIViewControllers
,我使用准备(segue)函数在两者之间发送数据。
在我的第一个视图控制器上,我使用Alamofire
但是当我使用prepare (segue)
,我的所有信息都是空的。
@IBAction func loginPage(_ sender: UIButton) {
let group = DispatchGroup()
Helper().alomofirePost(URL: "http://192.168.1.7/app_dev.php/login_check", Paramaters: paramaters) { contenuJSON in
if (contenuJSON["connected"].stringValue == "true") {
group.enter()
self.dashboad()
group.leave()
group.notify(queue: DispatchQueue.main) {
//print(self.image) // EMPTY
print(self.info[0]) // EMPTY FATAL ERROR INDEXT OUT OF RANGE
self.performSegue(withIdentifier: "Dashboard", sender: self)
}
}
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
if segue.identifier == "Dashboard" {
let success = segue.destination as! DashboardViewController
success.profil = self.image
}
}
func dashboad() {
// Other Function
//self.image = addPicProfil()
self.info = add_info(url: "http://192.168.1.7/app_dev.php/dashboard/info")
}
func add_info(url: String) -> [String] {
var info = [String]()
Helper().alomofireGet(URL: url) { contentJSON in
var content = contentJSON
print(content)
info.append(contentJSON["userFirstName"].stringValue)
info.append(contentJSON["countDevices"].stringValue)
info.append(contentJSON["earnedThisYearsEUR"].stringValue)
info.append(contentJSON["countCampaigns"].stringValue)
}
return (info)
}
在我的帮助文件中,我有:
func alomofireGet(URL: String, onCompletion:@escaping ((JSON) -> Void)) {
var contentJSON = JSON()
Alamofire.request(URL, method: .get).responseJSON() { (reponse) in
if reponse.result.isSuccess {
contentJSON = JSON(reponse.result.value!)
} else {
contentJSON = JSON(reponse.result.error!)
}
onCompletion(contentJSON)
}
}
func alomofirePost(URL: String, Paramaters: Dictionary<String, Any>, onCompletion: @escaping ((_ response: JSON) -> Void)) {
Alamofire.request(URL, method: .post, parameters: Paramaters).validate().responseJSON { (reponse) in
var contenuJSON = JSON()
if reponse.result.isSuccess {
contenuJSON = JSON(reponse.result.value!)
} else {
contenuJSON = JSON(reponse.result.error!)
}
onCompletion(contenuJSON)
}
}
你乱用 DispatchQueue info
is nil 因为你认为这
self.info = add_info(url: "http://192.168.1.7/app_dev.php/dashboard/info")
将添加附加的异步值,但它将返回一个空数组,您需要
func add_info(url: String,completion:@escaping(_ arr:[String]) -> ()) {
var info = [String]()
Helper().alomofireGet(URL: url) { contentJSON in
print(contentJSON)
info.append(contentJSON["userFirstName"].stringValue)
info.append(contentJSON["countDevices"].stringValue)
info.append(contentJSON["earnedThisYearsEUR"].stringValue)
info.append(contentJSON["countCampaigns"].stringValue)
completion(info)
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.