Search code examples
swiftswift5completionhandlerurlsession

Swift5 Extra argument 'completionHandler' in call error with session.dataTask


I am trying to make a some weather app but there is some problem The error is "Extra argument 'completionHandler' in call" what should i do for solve it ?? enter image description here

    import Foundation
    
    struct WeatherManager {
        let weatherURL = "http://api.openweathermap.org/data/2.5/weather?APPID=sdfkjskfjsfjskflskflsjklfjf&units=metric"
        
        func fetchWeather(cityName: String) {
           let urlStirng = "\(weatherURL)&q=\(cityName)"
            performRequest(urlString: urlStirng)
        }
        
        func performRequest(urlString: String) {
            //1. Create a URL
            if let url = URL(string: urlString) {
                
                //2. Create a URL Session
                let session = URLSession(configuration: .default)
                
                //3. Give the session a task
                let task = session.dataTask(with: url, completionHandler: handle(data:response:error:))
                
                //4. Start the task
                task.resume()
                
            }
        }
        
        func handle(data: Data?, response: URLSession?, error: Error?) {
            
        }
        
    }

Solution

  • Check the following code:

    func performRequest(urlString: String) {
    
        //1. Create a URL
        if let url = URL(string: urlString) {
            
            //2. Create a URL Session
            let session = URLSession(configuration: .default)
            
            //3. Give the session a task
            let task = session.dataTask(with: url, completionHandler: handle)
            
            //4. Start the task
            task.resume()
        }
    }
    
    func handle(data: Data?, response: URLResponse?, error: Error?) {
    
    }
    

    For response you need to pass an URLResponse instead of an URLSession to handle and you don't have to write the parameter names, because you are passing your handle function as an argument to dataTask.