AlertController in response to a URLSession

0

I try to modify the user data of an app through the connection with a web server which responds to this request with a boolean. The code implemented for the connection is fine because when checking the data, they are correctly reflected to those entered in the app. The problem is that when I check the server response I try to show a message but it always gives me an error. Please help

This is the code for the web service requirement

func Modificar(usuario:Usuario, completion: ((Bool) -> (Void))?){
    var respuesta: Bool = false
    if isConnectedToNetwork(){
        guard let url = URL(string: "\(DOMINIO)\(MODIFICARUSUARIO)") else { return }

        var request = URLRequest(url: url)
        request.httpMethod = "PUT"
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")  // the request is JSON

        let jsonObject: NSMutableDictionary = NSMutableDictionary()
        jsonObject.setValue("\(usuario.apellido)", forKey: "APELLIDOUSUARIO")
        jsonObject.setValue("\(usuario.ceduldaRuc)", forKey: "CEDULARUC")
        jsonObject.setValue("\(usuario.celular)", forKey: "CELULARUSUARIO")
        jsonObject.setValue("\(usuario.clave)", forKey: "CLAVEUSUARIO")
        jsonObject.setValue("1", forKey: "CODIGOPRIVILEGIO")
        jsonObject.setValue("\(usuario.id)", forKey: "CODIGOUSUARIO")
        jsonObject.setValue("\(usuario.correo)", forKey: "CORREOUSUARIO")
        jsonObject.setValue("ACTIVO", forKey: "ESTADO")
        jsonObject.setValue("/Date(1502920131070-0700)/", forKey: "FECHAACTUALIZACION")
        jsonObject.setValue("/Date(1502920131070-0700)/", forKey: "FECHAREGISTRO")
        jsonObject.setValue("\(usuario.nombre)", forKey: "NOMBREUSUARIO")

        var jsonResult: Data!
        do{
            jsonResult = try JSONSerialization.data(withJSONObject: jsonObject, options: []) as Data
        }catch{
            print("Error result")
        }
        request.httpBody = jsonResult

        let session = URLSession.shared
        session.dataTask(with: request){ (data, response, error) in
            do
            {
                respuesta = try JSONSerialization.jsonObject(with: data!, options: [.allowFragments, .mutableContainers]) as! Bool
                if respuesta
                {
                    completion?(true)

                }
                else
                {
                    completion?(false)

                }
            }
            catch
            {
                print(error)
            }
        }.resume()
    }
}

and that's how I use it when I click on a button on the interface

UsuarioExterno().Modificar(usuario: usuarioActual){ result in
if result
{
    Preferencia().modificar(parametro: "USUARIOSINCRONIZADO", valor:true)
}
else
{
    Preferencia().modificar(parametro: "USUARIOSINCRONIZADO", valor:true)
}
let alert = UIAlertController()
alert.title = "Mi app"
alert.addAction(UIAlertAction(title: "OK", style: .default,handler: nil))
alert.message =  self.usuarioActual.Modificar() ? "Todo bien" : "Todo mal"//copia en base local
self.present(alert, animated: true, completion: nil)

self.LimpiarCampos()
self.MostrarDatos(usuario: Usuario().buscar(incluirInactivo: false).firstObject as! Usuario)
}

Finally this is the error I get from the UIALERTCONTROLLER

Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '-[UIKeyboardTaskQueue waitUntilAllTasksAreFinished] may only be called from the main thread.'
    
asked by Kevtho 16.10.2017 в 01:06
source

1 answer

0

Your URLSession.dataTask is returning a closure in the background. As you are trying to show an alert from the background, it is not shown to you.

Try the following, in your Modify :

    let session = URLSession.shared
    session.dataTask(with: request){ (data, response, error) in
        do
        {
            respuesta = try JSONSerialization.jsonObject(with: data!, options: [.allowFragments, .mutableContainers]) as! Bool
            DispatchQueue.main.async {
                completion?(respuesta != nil)
            }
        }
        catch
        {
            print(error)
            DispatchQueue.main.async {
                 completion?(false)
            }
        }
    }.resume()
    
answered by 16.10.2017 в 11:06