Home > front end >  Data return issue in swiftUI from another function
Data return issue in swiftUI from another function

Time:08-10

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

CodePudding user response:

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)
  • Related