TDMNS
TDMNS

Reputation: 289

Problem converting link from string to urlProblem converting link from string to url

Today I ran into a problem, for some reason the url doesn't want to read the link. I don't know how to fix this problem. Everything that I write here: url = URL (string: "here"), for some reason, is not converted into a link. As I understand it, I get nil everywhere because I don't even go to let task = URLSession.shared.dataTask (with: url!), because url is not converted from string to URL.

func searchBarSearchButtonClicked(_ searchBar: UISearchBar) {
    // po searchBar.text
    // print object
    
    let urlString = "http://api.weatherstack.com/current?access_key=617ce097a4c8352ad4fa7b34e2570aa8&query=\(searchBar.text!)"
    
    let url = URL(string: urlString)
    
    var locationName: String?
    var temperature: Double?
    
    let task = URLSession.shared.dataTask(with: url!) { (data, response, error) in
        do {
            let json = try JSONSerialization.jsonObject(with: data!, options: .mutableContainers) as! [String : AnyObject]
            
            if let location = json["location"] {
                locationName = location["name"] as? String
            }
        
            if let current = json["current"] {
                temperature = current["temperature"] as? Double
            }
        }
        catch let jsonError {
            print(jsonError)
        }
    }
    task.resume()
}

Upvotes: 0

Views: 71

Answers (1)

David Pasztor
David Pasztor

Reputation: 54706

You should never force unwrap a URL created from a dynamic String which is coming from user input. You should optional bind the return value of URL(string:) and also percent encode your searchbar input to make sure the URL String is valid.

let urlString = "http://api.weatherstack.com/current?access_key=617ce097a4c8352ad4fa7b34e2570aa8&query=\(searchBar.text!)"
guard let encodedUrlString = urlString.addingPercentEncoding(withAllowedCharacters: .urlQueryAllowed), 
    let url = URL(string: encodedUrlString) else { 
    // You could display an error message to the user from here
    return
}

Unrelated to your question, but you shouldn't be using JSONSerialization to decode the JSON response. Use Codable instead.

Upvotes: 2

Related Questions