我创建了一个警报:
var a = 0 // default
let userAction = UIAlertController(title: "Select", message: "Select an action", preferredStyle: UIAlertControllerStyle.alert)
userAction.addAction(UIAlertAction(title: "action 1", style: .default, handler: { (action: UIAlertAction!) in
a = 1
}))
userAction.addAction(UIAlertAction(title: "action 2", style: .cancel, handler: { (action: UIAlertAction!) in
a = 2
}))
present(userAction, animated: true, completion: nil)
let resp = Just.get("http://localhost/\(a)").text
return resp
在此代码之后,我正在发送带有参数(a)的请求,但是在选择操作之前发送了请求。
我要如何等待用户选择警报并采取行动?
最佳答案
在类顶部声明typealias
import UIKit
typealias Request = ((_ value:String) -> ())
那么你的方法:-
func showPopup( completion:@escaping Request) {
var a = 0 // default
let userAction = UIAlertController(title: "Select", message: "Select an action", preferredStyle: UIAlertControllerStyle.alert)
userAction.addAction(UIAlertAction(title: "action 1", style: .default, handler: { (action: UIAlertAction!) in
a = 1
let resp = Just.get("http://localhost/\(a)").text
completion(resp)
}))
userAction.addAction(UIAlertAction(title: "action 2", style: .cancel, handler: { (action: UIAlertAction!) in
a = 2
let resp = Just.get("http://localhost/\(a)").text
completion(resp)
}))
self.present(userAction, animated: true, completion: nil)
}
并在需要的地方调用方法:
self.showPopup{ (value) in
print(value)
}