2016-11-19 88 views
0

是否有可能從另一個類訪問DispatchGroup? 說我有在類Loginfunctions.swift(具有var loginQueue = DispatchGroup.init()限定出func的)下面的函數:從另一個類訪問DispatchGroup

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

控制檯輸出是

Some other stuff... 
################# 
{ 
} 
More other stuff... 
***************** 
{ 
The Data I need : Out of the Closure 
} 

問題出在哪裏?

P.S.菜鳥在這裏;)

+0

,我們在您的使用了很多錯誤的'DispatchGroup'這裏 – KrishnaCA

+0

@KrishnaCA我相信你:d你能幫助我到底在哪? – Omep2005

+0

當異步調用完成時,每次調用DispatchGroup.enter()都應該由DispatchGroup.leave()進行平衡。即使在此任務完成之前,您正在調用DispatchGroup.leave()。你能告訴我你到底想要解決什麼問題嗎?你是否試圖在某處使用DispatchGroup.notify()?如果是這樣,那麼目的和目的是什麼? – KrishnaCA

回答

0

URLSessionTask方法本身是一個異步任務。所以,這裏不需要使用DispatchGroup。該logUserIn函數可以如下修改:

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

我愛你兄弟。萬分感謝!最後一個問題:你知道如何從關閉中獲得valueObj的值嗎?我試着定義一個實例,然後更新閉包中的值,但是因爲它是異步的,所以無法工作。 – Omep2005

+0

我試過它沒有這樣做:/在閉包中,值不爲空,但在關閉時調用print(dictionaryObj)將產生一個空的字典 – Omep2005

+0

您不應該在任務後嘗試打印它.resume()'行。這是一個異步過程。該值只有在該過程完成後纔會被捕獲。我認爲你需要先閱讀更多關於異步方法的知識。請查看這些文章。 http://swiftable.io/2016/06/dispatch-queues-swift-3/ – KrishnaCA