在Swift 4中使用信号量进行同步firebase查询

时间:2022-09-08 21:24:46

I'm trying to use a semaphore to have the code wait for the firebase query results.

我正在尝试使用信号量让代码等待firebase查询结果。

The code is the following:

代码如下:

var valor: Decimal = 0
let dateFormatter = DateFormatter()
let semaphore = DispatchSemaphore(value: 0)
dateFormatter.dateFormat = "mm/dd/yyyy"
//procedimenton para leitura dos dados no Firebase e jogar no array
Constants.refs.databaseRoot.child("Lancamentos").queryOrdered(byChild: "ContaDebito").queryEqual(toValue: "1.1.6").observe(.value, with: { snapshot in
    if let snapshots = snapshot.children.allObjects as? [DataSnapshot] {
        for snap in snapshots {
            if let postDict = snap.value as? Dictionary<String, AnyObject> {
                let post = FIRLancamento()
                post.setValuesForKeys(postDict)
                    let credito = post.Valor
                    valor += Decimal(string: credito)!
                print (credito + " " + String(describing: valor))

            }
        }
        semaphore.signal()
    }

})
semaphore.wait()
print(valor)

When I run this code, the semaphore signal never gets triggered and the program stays frozen, and I see the following error in the console:

当我运行此代码时,信号量信号永远不会被触发,程序保持冻结状态,我在控制台中看到以下错误:

2017-10-26 16:55:23.830048-0400 BVI_Swift[10830:1929792] TIC TCP Conn Failed [1:0x604000169a80]: 3:-9802 Err(-9802)
2017-10-26 16:55:23.831266-0400 BVI_Swift[10830:1929792] NSURLSession/NSURLConnection HTTP load failed (kCFStreamErrorDomainSSL, -9802)
2017-10-26 16:55:23.831597-0400 BVI_Swift[10830:1929792] Task . HTTP load failed (error code: -1200 [3:-9802])
2017-10-26 16:55:23.832476-0400 BVI_Swift[10830:1929780] Task . finished with error - code: -1200

If I comment the semaphore.wait() line, the query works perfeclty, but the print(valor) line is executed before it has any values.

如果我对semaphore.wait()行进行注释,则查询将完成,但print(valor)行在具有任何值之前执行。

1 个解决方案

#1


0  

Do you block main thread when you do this? As an example; if run this block inside button selector function and do not return; all application will freeze so semaphore.signal() will never executed.

你这样做时阻止主线程吗?举个例子;如果在按钮选择器功能内运行此块并且不返回;所有应用程序都将冻结,因此semaphore.signal()将永远不会执行。

Try running that block like this:

尝试像这样运行该块:

func buttonClick() {
   DispatchQueue.global(qos: .background).async {
      // your sync firebase operation
      // ...
   }
}

#1


0  

Do you block main thread when you do this? As an example; if run this block inside button selector function and do not return; all application will freeze so semaphore.signal() will never executed.

你这样做时阻止主线程吗?举个例子;如果在按钮选择器功能内运行此块并且不返回;所有应用程序都将冻结,因此semaphore.signal()将永远不会执行。

Try running that block like this:

尝试像这样运行该块:

func buttonClick() {
   DispatchQueue.global(qos: .background).async {
      // your sync firebase operation
      // ...
   }
}