swiftnsurlsessionnsurlsessiondatatasknsurlsessionconfiguration

Cannot invoke 'dataTask' with an argument list of type (with: NSMutableRequest, ...)


enter image description here

func performGetRequest(_ targetURL: URL!, completion: @escaping (_ data: Data?, _ HTTPStatusCode: Int, _ error: NSError?) -> Void) {
    let request = NSMutableURLRequest(url: targetURL)
    request.httpMethod = "GET"

    let sessionConfiguration = URLSessionConfiguration.default

    let session = URLSession(configuration: sessionConfiguration)

    let task = session.dataTask(with: request, completionHandler: { (data: Data?, response: URLResponse?, error: NSError?) -> Void in
        DispatchQueue.main.async(execute: { () -> Void in
            completion(data, (response as! HTTPURLResponse).statusCode, error)
        })
    })

    task.resume()
}

Here I am trying a demo from appCoda to integrate YouTube API. But not able to move further because of this method error :

Cannot invoke 'dataTask' with an argument list of type '(with: NSMutableURLRequest, completionHandler:(Data?, URLResponse..)'


Solution

  • Try this -

    func performGetRequest(_ targetURL: URL!, completion: @escaping (_ data: Data?, _ HTTPStatusCode: Int, _ error: NSError?) -> Void) {
        var request = URLRequest(url: targetURL)
        request.httpMethod = "GET"
    
        let sessionConfiguration = URLSessionConfiguration.default
    
        let session = URLSession(configuration: sessionConfiguration)
    
        let task = session.dataTask(with: request) { (data, response, error) in
            DispatchQueue.main.async(execute: { () -> Void in
                completion(data, (response as! HTTPURLResponse).statusCode, error)
            })
        }
    
        task.resume()
    }