我有一个Alamofire请求作为函数的一部分,我需要在执行其余函数之前完成请求。您可以在下面看到完整的功能。
@IBAction func btnScanPressed(_ sender: Any) {
// Retrieve the QRCode content
// By using the delegate pattern
readerVC.delegate = self
readerVC.completionBlock = { (result: QRCodeReaderResult?) in
print(result?.value)
Alamofire.request((result?.value)!).responseString { response in
debugPrint(response)
if let json = response.result.value {
let returnedJSON = JSON.init(parseJSON: json);
//TESTED -> this section does work and does update the values
self.co.setVideoURL(url: (returnedJSON["VideoURL"].string)!)
self.co.setDisplayText(text: returnedJSON["DisplayText"].string!)
self.co.setHasUpdated(value: true)
print("VARIABLES NOW SET")
}
}
}
// Presents the readerVC as modal form sheet (This needs to happen AFTER the Alamofire has completed)
readerVC.modalPresentationStyle = .formSheet
present(readerVC, animated: true, completion: nil)
}
我在那里使用swiftyJSON解析响应并为对象赋值。我需要在整个功能完成之前完成Alamofire请求。任何建议将不胜感激!
答案 0 :(得分:0)
基本上,您需要将Alamofire请求之后的代码移动到请求关闭中。请求闭包内的代码只会在请求成功完成或失败后触发(服务器错误,超时等)以下代码应该适合您。
@IBAction func btnScanPressed(_ sender: Any) {
// Retrieve the QRCode content
// By using the delegate pattern
readerVC.delegate = self
readerVC.completionBlock = { (result: QRCodeReaderResult?) in
print(result?.value)
Alamofire.request((result?.value)!).responseString { response in
debugPrint(response)
if let json = response.result.value {
let returnedJSON = JSON.init(parseJSON: json);
//TESTED -> this section does work and does update the values
self.co.setVideoURL(url: (returnedJSON["VideoURL"].string)!)
self.co.setDisplayText(text: returnedJSON["DisplayText"].string!)
self.co.setHasUpdated(value: true)
print("VARIABLES NOW SET")
// Presents the readerVC as modal form sheet (This needs to happen AFTER the Alamofire has completed)
self.readerVC.modalPresentationStyle = .formSheet
self.present(readerVC, animated: true, completion: nil)
}
}
}
}