datatask ios json http session swift

ios - datatask - urlrequest swift 4



waitUntilAllTasksAreFinished error Swift (4)

Con Xcode 8.0 y Swift 3, esto se ha modificado a la siguiente construcción:

OperationQueue.main.addOperation{ <your segue or function call> }

Recibo esta llamada en mi loginViewController cuando presiona el botón Enviar:

let http = HTTPHelper() http.post("http://someUrl.com/Login/userEmail//(username.text)/Pswd//(userPass.text)", postCompleted: self.checkLogin)

mientras que la función checkLogin que envío solo está realizando:

func checkLogin(succeed: Bool, msg: String){ if (succeed){ self.performSegueWithIdentifier("logInTrue", sender: self) } }

la función de publicación es HTTPHelper clase es:

func post(url : String, postCompleted : (succeeded: Bool, msg: String) -> ()) { var request = NSMutableURLRequest(URL: NSURL(string: url)!) var session = NSURLSession.sharedSession() request.HTTPMethod = "POST" var err: NSError? self.task = session.dataTaskWithURL(NSURL(string: url)!) {(data, response, error) in var strData = NSString(data: data, encoding: NSUTF8StringEncoding) var err: NSError? var json = NSJSONSerialization.JSONObjectWithData(data, options: .AllowFragments, error: &err) as? NSDictionary var msg = "No message" // Did the JSONObjectWithData constructor return an error? If so, log the error to the console if(err != nil) { let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding) postCompleted(succeeded: false, msg: "Error") } else { // The JSONObjectWithData constructor didn''t return an error. But, we should still // check and make sure that json has a value using optional binding. if let parseJSON = json { // Okay, the parsedJSON is here, let''s get the value for ''success'' out of it if let success = parseJSON["result"] as? Bool { postCompleted(succeeded: success, msg: "Logged in.") } return } else { // Woa, okay the json object was nil, something went worng. Maybe the server isn''t running? let jsonStr = NSString(data: data, encoding: NSUTF8StringEncoding) postCompleted(succeeded: false, msg: "Error") } } } self.task!.resume() }

cuando se llama a la función checkLogin con éxito: true no ejecuta la funciónSegueWithIdentified .. el error es similar a:

Fallo de aserción en - [UIKeyboardTaskQueue waitUntilAllTasksAreFinished], /SourceCache/UIKit_Sim/UIKit-3318.16.14/Keyboard/UIKeyboardTaskQueue.m:374 2014-11-15 17: 41: 29.540 Wavesss [8462: 846477] *** Aplicación de terminación debido a excepción no detectada ''NSInternalInconsistencyException'', razón: ''- [UIKeyboardTaskQueue waitUntilAllTasksAreFinished] solo se puede invocar desde el hilo principal.''

por favor, ayúdenme, aunque estoy luchando mucho para encontrar una solución para esto, parece que no puedo pasar entre los controladores de vista mientras la url aún se está ejecutando en otro hilo. gracias de antemano chicos!


Estaba teniendo este problema al tratar de cambiar el contenido de un cuadro de texto desde el interior de una tarea Async.

La solución estaba usando DispatchQueue (Xcode 8.0 y Swift 3.0):

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1) { self.textBox.text = "Some Value" }


Su función checkLogin se está llamando en otro hilo, por lo que debe volver al hilo principal antes de poder llamar a self.performSegueWithIdentifier . Prefiero usar NSOperationQueue :

func checkLogin(succeed: Bool, msg: String) { if (succeed) { NSOperationQueue.mainQueue().addOperationWithBlock { self.performSegueWithIdentifier("logInTrue", sender: self) } } }


También estaba teniendo el mismo problema, se resolvió tomando la referencia de la respuesta anterior. Gracias @Nate

var storyBoard: UIStoryboard = UIStoryboard(name: "Main", bundle: nil) var vc: UINavigationController = storyBoard.instantiateViewControllerWithIdentifier("AppViewController") as! UINavigationController NSOperationQueue.mainQueue().addOperationWithBlock { self.presentViewController(vc, animated: true, completion: nil) }