使用调度组时关闭丢失

时间:2019-07-10 11:05:36

标签: swift closures

未调用调度代码。当我调用reLog()方法时,它未执行在DispatchQueue.main.async块中编写的代码。

       func reLog() -> Bool {
            var isVerified = false
            let group = DispatchGroup()
            group.enter()
            DispatchQueue.global(qos: .default).async {
                    self.login({ () -> Void in
                        isVerified = true
                        group.leave()
                    }, fail: { (failureDict) -> Void in
                        group.leave()
                    })
                }
            group.wait() 
            return isVerified
        }


        func login(_ success : (()-> Void), fail : (()-> Void)){
             let session = URLSession(configuration: .default, delegate: self, delegateQueue: nil)
             let task = session.dataTask(with: urlRequest){
                (data, response, error) -> Void in
                  DispatchQueue.main.async(execute: { () -> Void in
                       print("Testing")   // This closure not calling
                  })
             })
             task.resume()
        }

现在这是我的要求。我需要实现这一点,因为我需要服务器响应才能继续循环。

for i in strings {
     let isLogged = relog()
     if isLogged {
        print("Successful")
    }
}

2 个答案:

答案 0 :(得分:2)

您需要在#!/bin/bash while read -r line; do echo "${line% *} $(openssl rand -base64 18)" done < secrets.ini > new_secrets.ini

login

替换

task.resume()

使用

group.wait() 
return isVerified

group.notify(queue:.main) {
  completion(isVerified)
}

编辑

func reLog(completion:@escaping(Bool) -> ())

致电

func reLog(completion:@escaping(Bool) -> ())
            var isVerified = false
            let group = DispatchGroup()
            group.enter()
            DispatchQueue.global(qos: .default).async {
                    self.login({ () -> Void in
                        isVerified = true
                        group.leave()
                    }, fail: { (failureDict) -> Void in
                        group.leave()
                    })
                }
        group.notify(queue:.main) {
          completion(isVerified)
        } 
 }

答案 1 :(得分:0)

不调用闭包,因为您将delegate的{​​{1}}设置为URLSession,这需要采用协议并实现委托方法。

self委托使用init方法

nil

您正在滥用let session = URLSession(configuration: .default) let task = session.dataTask(with: urlRequest) { 来使异步任务同步。这是非常糟糕的做法。