我试图建立一个用户regeistration窗体,它应该检查用户是否已经存在。所以我发送一个php请求到我的mysql服务器。如果返回值为空,则用户尚未存在。如何等待下载任务快速完成3
Unfortunatley我真的坚持等待这个检查完成。我尝试了几个解决方案,我发现谷歌,但没有一个工作。我当前的代码使用信号量,并将崩溃“致命错误:意外地发现零,而解包可选值”,所以信号量不会等待,直到任务完成,因为我期望它。
任何提示,将不胜感激。多谢你们。
private func isUniqueEmail(email: String) -> Bool {
var result: Bool?
let semaphore = DispatchSemaphore(value: 1)
let requestURL = URL(string: "http://localhost/firstpostget/functions/get.php")
var request = URLRequest(url: requestURL!)
request.httpMethod = "POST"
let postParameters = "email=" + email
request.httpBody = postParameters.data(using: .utf8)
let configuration = URLSessionConfiguration.default
let session = URLSession(configuration: configuration, delegate: nil, delegateQueue: OperationQueue.main)
let task = session.dataTask(with: request) {(data, response, error) in
var myJson: AnyObject
do{
myJson = try JSONSerialization.jsonObject(with: data!, options: JSONSerialization.ReadingOptions.mutableContainers) as AnyObject
if myJson.count == 0{
result = true
semaphore.signal()
} else{
result = false
semaphore.signal()
}
} catch{
//TODO
print(error)
}
}
task.resume()
semaphore.wait(timeout: .distantFuture)
return result!
}
请勿“等待”。不要使用SEMAPHORES。 – matt