0

I use wheaterapi.com and create url with init URL(string: urlString). If I use the received url in a browser, I can get valid answer, and get all data, but if I use url with my app I get error. How fix it?

func ferchFromServer(cityName: String) {
    let urlString = "https://api.weatherapi.com/v1/current.json?key=\(apikey!)&q=\(cityName)"
    let url = URL(string: urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed)!)
    print(url!)
    let session = URLSession(configuration: .default)
    let task = session.dataTask(with: url!) { (data, response, error) in
        if let receivedData = data {
            if let datas = self.parseJSON(data: receivedData){
                self.delegate?.updateInterface(self, datas: datas)
            }

        }
    }
    task.resume()
}

print(url) > https://api.weatherapi.com/v1/current.json?key=<MYKEY>&q=New%20York its valid url and if entered it in a text field of browser, its work (instead MYKEY - my valid key)

but app return > The data couldn’t be read because it isn’t in the correct format.

P.S. if I try use city from 1 word (for example Moscow of Stambul) code working and don't return this error

1 Answers1

0

Below code can be used to call the weather api.

//Calling the method with required city name

    let queryParams = ["q": "new york", "key":"your_key"]

            sendRequest("https://api.weatherapi.com/v1/current.json", parameters: queryParams) { responseObject, error in
                guard let responseObject = responseObject, error == nil else {
                    print(error ?? "Unknown error")
                    return
                }
                 print(responseObject)
                // use `responseObject` here
            }

Get request

func sendRequest(_ url: String, parameters: [String: String], completion: @escaping ([String: Any]?, Error?) -> Void) {
            var components = URLComponents(string: url)!
            components.queryItems = parameters.map { (key, value) in
                URLQueryItem(name: key, value: value)
            }
            components.percentEncodedQuery = components.percentEncodedQuery?.replacingOccurrences(of: "+", with: "%2B")
            let request = URLRequest(url: components.url!)

            let task = URLSession.shared.dataTask(with: request) { data, response, error in
                guard let data = data,                            // is there data
                    let response = response as? HTTPURLResponse,  // is there HTTP response
                    (200 ..< 300) ~= response.statusCode,         // is statusCode 2XX
                    error == nil else {                           // was there no error, otherwise ...
                        completion(nil, error)
                        return
                }

                let responseObject = (try? JSONSerialization.jsonObject(with: data)) as? [String: Any]
                completion(responseObject, nil)
            }
            task.resume()
        }