简体   繁体   中英

How to use dispatch_async in Swift?

I want to send some data to the server but when I try , I get this error

在此处输入图片说明

I think is a problem with dispatch maybe I am not using it correctly but I have no experience with xcode or swift, so I don't know how to understand well the log error window, any help is welcome, thaks for ur time

This is my code:

func updateAndDismiss6() {
    SharingManager.sharedInstance.FinalDiag = self.Diag.text!
    SharingManager.sharedInstance.TreatmentDays = self.Trata.text!
    SharingManager.sharedInstance.SystematicTreat = self.TrataSu.text!
    SharingManager.sharedInstance.LidoPatch = self.ParcheLido.text!
}

@IBAction func IrResumen(sender: AnyObject) {

    updateAndDismiss6()

    let prefs = NSUserDefaults.standardUserDefaults()
    let userid = prefs.stringForKey("userid")! as String

    let Inicial = SharingManager.sharedInstance.Initials
    let Edad = SharingManager.sharedInstance.Age
    let Resultados = SharingManager.sharedInstance.Result
    let Diagnostico = SharingManager.sharedInstance.FinalDiag
    let Ttratamiento = SharingManager.sharedInstance.TreatmentDays
    let TsUsado = SharingManager.sharedInstance.SystematicTreat
    let Plidocaina = SharingManager.sharedInstance.LidoPatch




    if ( Inicial == "" || Edad == "" || Resultados == "" || Diagnostico == "" || Ttratamiento == "" || TsUsado == "" || Plidocaina == "" || userid == "") {

        let alertView:UIAlertView = UIAlertView()
        alertView.title = "No data"
        alertView.message = "error de datos"
        alertView.delegate = self
        alertView.addButtonWithTitle("OK")
        alertView.show()
    }
    else {



        let url_servicio = "http://arasoftltda.com/grunenthal/app/muestra.php"

        let request = NSMutableURLRequest(URL: NSURL(string: url_servicio)!)
        request.HTTPMethod = "POST"
        //let postString = "nombre=pruebafromios&email=pruebafromios@pruebafromios.com&registro=registro&esp=esp&pais=Colombia&ciudad=Cogua&contrasena=123"
        let postString =  "iniciales=\(Inicial)&edad=\(Edad)&resultado=\(Resultados)&diagnostico=\(Diagnostico)&dias=\(Ttratamiento)&tratamiento=\(TsUsado)&parche=\(Plidocaina)&id=\(userid)"
        request.HTTPBody = postString.dataUsingEncoding(NSUTF8StringEncoding)
        let task = NSURLSession.sharedSession().dataTaskWithRequest(request) { data, response, error -> Void in
             if (error != nil){
            print(error!.localizedDescription)
            } else{
                let nsdata:NSData = NSData(data: data!)

                do{
                    let json = try NSJSONSerialization.JSONObjectWithData(nsdata, options: NSJSONReadingOptions.MutableContainers)
                    let id = json["id"] as! String



                    if (id != ""){
                        print (id)

                        dispatch_async(dispatch_get_main_queue()) {
                            [unowned self] in
                            self.performSegueWithIdentifier("Resumen", sender: self)}
                    }

                }

                catch{
                    print("Error del JSON")
                    let alertView:UIAlertView = UIAlertView()
                    alertView.title = "Fallo al enviar datos!"
                    alertView.message = "Error de conexion con el servidor"
                    alertView.delegate = self
                    alertView.addButtonWithTitle("OK")
                    alertView.show()
                }
                }

        }
        task.resume()

    }

    }

Your error message is telling you that it tried to update the UI (in this case, the auto layout constraints) from a background thread. The presence of numerous UIAlertView and UIAlertController references in the stack trace is telling you that the source of the problem is the UIAlertView .

Bottom line, all UI updates must be dispatched to the main queue. So, in addition to dispatching performSegueWithIdentifier to the main queue, you must dispatch your UIAlertView / UIAlertController to the main queue, too.

func showError() {
        dispatch_async(dispatch_get_main_queue()) { [unowned self] in
            let ac = UIAlertController(title: "Loading error", message: "There was a problem loading the feed; please check your connection and try again.", preferredStyle: .Alert)
            ac.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
            self.presentViewController(ac, animated: true, completion: nil)
        }
    }

You are doing it while performing segue. Try the same thing while showing alerts!!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM