从另一个类访问DispatchGroup

时间:2016-11-19 22:30:00

标签: swift swift3 grand-central-dispatch xcode8 dispatch-async

是否可以从另一个类访问DispatchGroup? 假设我在班级function ota() { '/cygdrive/d/Program Files (x86)/Arduino/hardware/esp8266com/esp8266/tools/espota.py' "$@" } 中有以下功能(Loginfunctions.swift中定义了var loginQueue = DispatchGroup.init()):

func

从另一个类(func logUserIn(emaila: String!, passworda: String!, urlPath: String!, completionHandler:@escaping (NSDictionary) -> Void) { DispatchQueue.global(qos: .userInitiated).async { let requestURL = NSURL(string: urlPath)! let request = NSMutableURLRequest(url: requestURL as URL) request.httpMethod = "POST" let emailtext = emaila let passwordtext = passworda let postParameters = "email="+emailtext!+"&password="+passwordtext!; request.httpBody = postParameters.data(using: .utf8) DispatchGroup.enter(loginQueue)() //creating a task to send the post request let task = URLSession.shared.dataTask(with: request as URLRequest) { data, response, error in if error != nil{ print("error is \(error)") return; } do { //converting resonse to NSDictionary let myJSON = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary DispatchGroup.wait(self.loginQueue)() DispatchQueue.main.async { completionHandler(myJSON) } } catch { print(error) } } //executing the task task.resume() DispatchGroup.leave(self.loginQueue)() } } )调用以下内容会导致LoginViewController.swift的不同值(TEMP_VAR_FOR_LOGIN中的实例):

LoginViewController.swift

控制台输出

@IBAction func userLogin(_ sender: UIButton) {
            self.loginFunctions.logUserIn(emaila: self.email.text, passworda: self.password.text, urlPath: "URL_PATH_WAS_ENTERED_HERE")   {
                (completionHandler) in
                self.TEMP_VAR_FOR_LOGIN = completionHandler
                print("*****************")
                print(self.TEMP_VAR_FOR_LOGIN)
            }

            print("################")
            print(TEMP_VAR_FOR_LOGIN)
}

问题所在的任何帮助?

P.S。新秀在这里;)

1 个答案:

答案 0 :(得分:0)

URLSessionTask方法本身是一个异步任务。因此,此处无需使用DispatchGrouplogUserIn函数可以修改如下:

func logUserIn(emaila: String!, passworda: String!, urlPath: String!, completionHandler:@escaping (NSDictionary) -> Void)  {

    let emailtext = emaila
    let passwordtext = passworda

    let postParameters = "email="+emailtext!+"&password="+passwordtext!;

    let requestURL = URL(string: urlPath)!
    var request = URLRequest(url: requestURL)
    request.httpMethod = "POST"
    request.httpBody = postParameters.data(using: .utf8)

    //creating a task to send the post request
    let session = URLSession(configuration: URLSessionConfiguration.default)
    let task: URLSessionDataTask = session.dataTask(with: request, completionHandler: { data, response, error in

        if error != nil {
            print(error)
        }else {
            do {
                //converting resonse to NSDictionary
                let myJSON =  try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! NSDictionary
                DispatchQueue.main.async {
                    completionHandler(myJSON)
                }
            } catch {
                print(error)
            }
        }
    })

    task.resume()
}

其次,你在这里使用closure的方式是错误的。它的用法如下:

var dictionaryObj:NSMutableDictionary = NSMutableDictionary() //global - defined outside functions

self.logUserIn(emaila: "lal", passworda: "lal", urlPath: "lal", completionHandler: { dictionaryObj in
    self.dictionaryObj = dictionaryObj as! NSMutableDictionary
    print(dictionaryObj)
    print(self.dictionaryObj)
})