1

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

user2924482
  • 8,380
  • 23
  • 89
  • 173

2 Answers2

1

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()
    }
jnpdx
  • 45,847
  • 6
  • 64
  • 94
1

Change

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

To

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

Call it as

URLSession.doSomethingElse...
matt
  • 515,959
  • 87
  • 875
  • 1,141