是否有可能從另一個類訪問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.菜鳥在這裏;)
,我們在您的使用了很多錯誤的'DispatchGroup'這裏 – KrishnaCA
@KrishnaCA我相信你:d你能幫助我到底在哪? – Omep2005
當異步調用完成時,每次調用DispatchGroup.enter()都應該由DispatchGroup.leave()進行平衡。即使在此任務完成之前,您正在調用DispatchGroup.leave()。你能告訴我你到底想要解決什麼問題嗎?你是否試圖在某處使用DispatchGroup.notify()?如果是這樣,那麼目的和目的是什麼? – KrishnaCA