Here is my code in UploadModel.swift
func uploadSpecialistWithId(login: String, password: String) {
let requestUrl = URL(string: "http://localhost:3000/api/register/specialist")!
var request = URLRequest(url: requestUrl)
request.httpMethod = "POST"
let postParams = "login=\(login)&password=\(password)"
print(postParams)
request.httpBody = postParams.data(using: String.Encoding.utf8)
let task = URLSession.shared.dataTask(with: request) {(data, response, error)
in
if(error != nil) {
print("error -> \(error!.localizedDescription)")
} else {
print("data uploaded")
self.parseJSONSpecialistResponse(data: data!)
}
}
task.resume()
}
func parseJSONSpecialistResponse(data: Data) {
var jsonResult = NSDictionary()
let specialist = Specialist()
do {
jsonResult = try JSONSerialization.jsonObject(with: data, options: .allowFragments) as! NSDictionary
} catch let error as NSError {
print("error -> \(error.localizedDescription)")
}
let items = NSMutableArray()
if let login = jsonResult["login"] as? String,
let specialistId = jsonResult["_id"] as? String {
specialist.login = login
specialist.specialistId = specialistId
print("Added \(specialist.itemDescribtion())")
items.add(specialist)
} else {
let errorCode = jsonResult["code"] as! Int
print("Erorr with code -> \(errorCode)")
items.add(errorCode)
}
DispatchQueue.main.async(execute: { () -> Void in
self.delegate.itemsUploaded(items: items)
})
}
But when i was trying to reg the specialist with existing login the segue had performed before i handled the server response. What should I change to solve this problem? Here is my code in ViewController.swift
func itemsUploaded(items: NSArray) {
if let errorCode = items[0] as? Int {
if errorCode == 11000 {
warningLabel.text = "This login is already used"
error = true
}
}
if let specialist = items[0] as? Specialist {
self.specialistId = specialist.specialistId!
print("Value after itemsUploaded --> \(self.specialistId)")
}
}
@IBAction func doneButtonTouched(_ sender: Any) {
uploadModel.uploadSpecialistWithId(login: loginTextField.text!, password: passwordTextField.text!)
if(error == false) {
print("Segue perform value -> \(specialistId)")
performSegue(withIdentifier: "regToRegCompleteSegue", sender: self)
}
}
override func prepare(for segue: UIStoryboardSegue, sender: Any?) {
let destination = segue.destination as! RegistrationCompleteViewController
print("Segue prepare value -> \(specialistId)")
destination.specialistId = self.specialistId
}
I understand that i have this issue because of asynchronously of dataTask. But why does it not working when the self.delegate is already in the main queue?
EDIT: Adding a completionHandler didn't solve my problem, but Kamran's offer is working.