等待用户迅速响应

时间:2018-02-07 08:39:08

标签: ios swift alert

我创建了一个提醒:

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)的请求,但在选择操作之前发送请求。 我怎么能等到用户从警报中选择并采取行动?

4 个答案:

答案 0 :(得分:3)

在类之上声明类型

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)
}

答案 1 :(得分:0)

移除call function电话下方的present。将其移至警报按钮操作结束

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
    // Call function here
}))

userAction.addAction(UIAlertAction(title: "action 2", style: .cancel, 
handler: { (action: UIAlertAction!) in
    a = 2
    // Call function here
}))

present(userAction, animated: true, completion: nil)

答案 2 :(得分:0)

你可以使用信号量等待进程直到获得信号。

查看本教程https://medium.com/swiftly-swift/a-quick-look-at-semaphores-6b7b85233ddb,它是GCD的,但我们也可以将它用于主队列。

只需创建let semaphore = DispatchSemaphore(value: 1),然后semaphore.wait() - 等待其通过semaphore.signal()获取信号。

有关详细信息,请查看教程链接。

答案 3 :(得分:0)

尝试这样做

 let alertView = UIAlertController.init(title: "Enviado com sucesso!", message: "O seu bilhete foi enviado com sucesso", preferredStyle: .alert)

 let OKAction = UIAlertAction(title: "OK", style: .default) { action in
        //the Code you place here Will be called after user Select an action
 }
 alertView.addAction(OKAction)
 self.present(alertView, animated: true, completion: nil)