Home > Enterprise >  Swift: URLSession extension configuration error: Cannot call value of non-function type 'URLSes
Swift: URLSession extension configuration error: Cannot call value of non-function type 'URLSes

Time:11-14

I have this function:

class myClass: ObservableObject {
    
    func doSomethingElse<T:Decodable>(url: URL,
                                      config: URLSessionConfiguration,
                                      type: T.Type) -> AnyPublisher<Int, any Error> {
        return URLSession(configuration:config).dataTaskPublisher(for: url)
            .tryMap{ response in
                guard let valueResponse = response.response as? HTTPURLResponse else {
                    return 000
                }
                return valueResponse.statusCode
            }.mapError{error in
                return error
            }
            .eraseToAnyPublisher()
    }
}

and it works just fine but I'm trying to add this function to URLSession extension:

extension URLSession {
    
    func doSomethingElse<T:Decodable>(url: URL,
                                      config: URLSessionConfiguration,
                                      type: T.Type) -> AnyPublisher<Int, any Error> {
       return self(configuration:config).dataTaskPublisher(for: url)
            .tryMap{ response in
                guard let valueResponse = response.response as? HTTPURLResponse else {
                    return 000
                }
                return valueResponse.statusCode
            }.mapError{error in
                return error
            }
            .eraseToAnyPublisher()
    }

But I'm getting this error:

enter image description here

Cannot call value of non-function type 'URLSession'

Any of you knows why I'm getting this error? or how can configure URLSession to have the configuration?

I'll really appreciate your help

CodePudding user response:

self is the specific instance of URLSession. You want Self, which is the type

Self(configuration:config)...

You may also want doSomethingElse to be a static function, since it doesn't actually reference the specific instance of self:

static func doSomethingElse<T:Decodable>(url: URL,
                                      config: URLSessionConfiguration,
                                      type: T.Type) -> AnyPublisher<Int, any Error> {
        return Self(configuration:config).dataTaskPublisher(for: url)
            .tryMap{ response in
                guard let valueResponse = response.response as? HTTPURLResponse else {
                    return 000
                }
                return valueResponse.statusCode
            }.mapError{error in
                return error
            }
            .eraseToAnyPublisher()
    }

CodePudding user response:

Change

func doSomethingElse...{
   return self(configuration:...

To

static func doSomethingElse...{
   return Self(configuration:...

Call it as

URLSession.doSomethingElse...
  • Related