Problem Swift with Webservice

0

Hi, I'm doing a simple app to learn how to use WebService but I have a problem.

On the line where I initialize task I get the following error when I execute it and I give the button to call the service .

  

Thread 1: Fatal error: Unexpectedly found nil while unwrapping an Optional value

func llamadaWebService(){

        let urlPath = "http://api.openweatherapp.rg/data/2.5/weather?q=\(String(describing: captura.text))"

        let url = URL(string: urlPath)

        let session = URLSession.shared

        let task = session.dataTask(with: url!) { (data, response, error) in

            if(error != nil) {

                //Imprime error si no está vacío . Si hay error es que hubo error en la conexión

                print("error")
            }

            let nsdata:NSData = NSData(data: data!)

            print(nsdata)

        //    self.recuperarClimaDeJson(nsdata)
        }
        task.resume()
}

Thanks in advance.

    
asked by Javi Cholbi 17.07.2018 в 23:33
source

1 answer

0

To start your url is wrong to try this and it worked: " link ".

I recommend using optional instead of forcing unwrap (Use a variable when you do not know if it has a value or is null).

Probably nsdata is the cause of the error (Certainly you do not need to convert Data to NSData). This null for that gives you that error when you want to print.

I recommend you read some Swift 4.

Finally you must add the NSAppTransportSecurity key to your info.plist file to allow the connection to http; right click-open as-source code. and within the first dic that appears it sticks this (This is not the best way to do it but it is the fastest):

<key>NSAppTransportSecurity</key>
<dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
</dict>

Here is an example that is not going to send any code errors but will not do the query either because I do not have a Key for the API, the data object is also converted to a dictionary (It is also not the best way, for this reads a bit of Codable, Encodable and Decodable):

func task() {
    let captura = "phoenix"
        let urlPath = "http://api.openweathermap.org/data/2.5/weather?q=\(String(describing: captura))"

    guard let url = URL(string: urlPath) else{
        print("URL invalida")

        return
    }

        let session = URLSession.shared

        let task = session.dataTask(with: url) { (data, response, error) in

            if let error = error{
                print("ERROR: \(error)")
            }

            guard let unwrappedData = data else{
                 print("Datos vacios algo salio mal")
                return
            }

            do{

                guard let json = try JSONSerialization.jsonObject(with: unwrappedData, options: []) as? [String: Any] else{
                    print("Error en el json")
                    return
                }

                print(json)


            }catch{
                print("No se pudo convertir el objeto a un Diccionario")
            }



            //    self.recuperarClimaDeJson(nsdata)
        }
        task.resume()
    }
    
answered by 18.07.2018 в 16:39