1

Below is my code which is calling an API and performing action as per the code

import Foundation

class apiCall {
    func getUsers(completion:@escaping ([Result]) -> ()) {
        
        let url = URL(string: "http://myapi-call-ges-here")!
        var request = URLRequest(url: url)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.httpMethod = "GET"

        URLSession.shared.dataTask(with: request) { (data, response , error) in
     
            do{
                let result = try JSONDecoder().decode(Result.self,from: data!)
                print(result)
                
            }
            catch{
                print("Error:\(error)")
            }
         }.resume()
        }
}

But I want to do code clean up and wanted to keep API calling code in different file as shown below

import Foundation

class apiCall {
    func getUsers(completion:@escaping ([Result]) -> ()) {

      let request=apiParamfunc()

        URLSession.shared.dataTask(with: request) { (data, response , error) in

            do{
                let result = try JSONDecoder().decode(Result.self,from: data!)
                print(result)

            }
            catch{
                print("Error:\(error)")
            }
         }.resume()
        }
}

apiParamfunc is a function which is created in another file

import Foundation
 funct apiParamfunc-> Any{

     let url = URL(string: "http://myapi-call-ges-here")!
        var request = URLRequest(url: url)
        request.addValue("application/json", forHTTPHeaderField: "Content-Type")
        request.addValue("application/json", forHTTPHeaderField: "Accept")
        request.httpMethod = "GET"
   
       return request


}

but I am getting an error for dataTask as "No exact matches in call to instance method 'dataTask' ". I even tried with different datatype but not getting any helpful thing,please help me on this

1 Answer 1

1

You cannot use Any, but specify exact type, like

 funct apiParamfunc() -> URLRequest {     // << here !!

     let url = URL(string: "http://myapi-call-ges-here")!
     var request = URLRequest(url: url)
Sign up to request clarification or add additional context in comments.

1 Comment

this worked fine for me, I was looking for this data type URLRequest

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.