iosobjective-cswiftalamofireobjective-c-swift-bridge

iOS: How to user a specific function from my swift class in objective C? `Use of undeclared identifier 'NetworkClient'`


I use this code in Swift that works well, but impossible to call it in Objective C.

import Foundation
import Alamofire


enum Router: URLRequestConvertible {
  case users

  static let baseURLString = "https://api.stackexchange.com/2.2"

  func asURLRequest() throws -> URLRequest {
    let path: String
    switch self {
    case .users:
      path = "/users?order=desc&sort=reputation&site=stackoverflow&max=10"
    }

    let url = URL(string: Router.baseURLString + path)!
    return URLRequest(url: url)
  }
}

@objcMembers public final class NetworkClient {
  // 1
  let evaluators = [
    "api.stackexchange.com":
      PinnedCertificatesTrustEvaluator(certificates: [
        Certificates.stackExchange
        ])
  ]

  let session: Session

  // 2
  private init() {
    session = Session(
      serverTrustManager: ServerTrustManager(evaluators: evaluators)
    )
  } ...

I use it like this under Swift :

 NetworkClient.request(Router.users)
      .responseDecodable { (response: DataResponse<UserList>) in
        switch response.result {
        case .success(let value):
          self.users = value.users
        case .failure(let error):
          let isServerTrustEvaluationError =
            error.asAFError?.isServerTrustEvaluationError ?? false
          let message: String
          if isServerTrustEvaluationError {
            message = "Certificate Pinning Error"
          } else {
            message = error.localizedDescription
          }
          self.presentError(withTitle: "Oops!", message: message)
        }
      }

I tried this under Objective C with no success:

NetworkClient.request.responseDecodable()
    {

    }

The error message is: Use of undeclared identifier 'NetworkClient'

Any ideas? Thanks in advance.


Solution

  • You need your Swift class to inherit from NSObject for it to be visible to Objective-C.

    public final class NetworkClient: NSObject {
       // ...
    }