Swift函数异步

时间:2018-03-24 08:37:14

标签: ios swift xcode alamofire

func passcodeViewController(_ passcodeViewController: TOPasscodeViewController, isCorrectCode code: String) -> Bool {

        let userDefault = UserDefaults.standard
        let tokenPinCode = userDefault.string(forKey: "tokenPinCode")
        let mailData = self.emailField.text
        let dataStruct = mailData!+"|"+tokenPinCode!
        print("1")
        self.checkToken(code: dataStruct) { (response) in
            if(response[0] == "OK"){
                print("2")
                self.alertPasswordChange(text: "Podaj nowe hasło", code: dataStruct)
            }else{
                self.standardAlert(title: "Znaleziono błędy", message: "Podany kod jest błedny", ok: "Rozumiem")
                self.werifyButton.isEnabled = true
            }
        }
        print("3")
        return false
    }

功能返回:打印 - > 1 - > 3 - > 2

如何解决问题:打印 - > 1 - > 2 - > 3

3 个答案:

答案 0 :(得分:1)

使你的函数无效并传递可以处理bool值的完成处理程序。

function test()
{
var s = this.getField("Order01");
    if(!event.willCommit)
    {
        if (event.change == "Sell") 
    {
      this.resetForm(s);
          s.fillColor = color.red;
      s.value = "Sell Order";

    }
    else if (event.change =="Buy")
    {
      this.resetForm(s);
          s.fillColor = color.green;
      s.value = "Buy Order";

    }
              else if (event.change=="Transaction")
    {
      this.resetForm(s);
          s.fillColor = color.transparent;
      s.value = " ";
    }
     }
}

你可以这样称呼:

func passcodeViewController(_ controller: Controller, code: String, @escaping handler: (Bool) -> ()) {
  // Your logic
  asyncRequest(...) {
    response in
    let result = ... // find whether code ok
    handler(result)
  }
}

答案 1 :(得分:0)

您可以使用信号量实现此功能。信号量提供等待功能完成的功能。请看下面的代码。

let serialQueue = DispatchQueue(label: "co.random.queue")

func funcA() {
    print("Print A")

    let semaphore = DispatchSemaphore(value: 1)

    serialQueue.async {
        print("Print B")
        semaphore.signal()
    }
    semaphore.wait()

    print("Print C")
}

funcA()

上面的代码是用异步函数执行的,我在playground中实现了它打印后输出;

Print A
Print B
Print C

我删除信号量然后打印为:

Print A
Print C
Print B

我希望这对你有用。

答案 2 :(得分:-1)

使您的函数无效并通过签名

传递完成处理程序