如何在Swift中使用dispatch_async?

时间:2016-08-11 00:28:23

标签: ios swift swift2

我想将一些数据发送到服务器,但是当我尝试时,我收到此错误

enter image description here

我觉得调度问题可能是我没有正确使用它但我没有使用xcode或swift的经验,所以我不知道如何理解日志错误窗口,欢迎任何帮助,thaks为你的时间

这是我的代码:

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()

    }

    }

2 个答案:

答案 0 :(得分:2)

您的错误消息告诉您它尝试从后台线程更新UI(在本例中为自动布局约束)。堆栈跟踪中存在大量UIAlertViewUIAlertController引用,告诉您问题的根源是UIAlertView

从底线开始,必须将所有UI更新分派到主队列。因此,除了将performSegueWithIdentifier发送到主队列之外,您还必须将UIAlertView / UIAlertController发送到主队列。

答案 1 :(得分:1)

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)
        }
    }

您在执行segue时正在执行此操作。在显示警报时尝试相同的事情!!