iOS Networking - Moya & Protocol Buffer Serialisation

171 views Asked by At

Can anyone elaborate me on the possibility of using Moya for communicating with web services that use ProtoBuf Serialisation instead of JSON notation? Is it possible? Is it already implemented or is there any extensions for it? Any information is really appreciated :)

1

There are 1 answers

0
saroj raut On

Yes it is possible

Here is the process how you can use protobuf with Moya.

import Foundation
import Moya
import SwiftProtobuf


 enum Currency {
   case exchangeRate(param: SwiftProtobuf.Message)
 }

 extension Currency: TargetType {

     var validationType: ValidationType {
    
         return .successCodes
     }

     var headers: [String: String]? {
   
         return [
           "Accept":        "application/octet-stream",
           "Content-Type":  "application/octet-stream",
           "Authorization": [use auth token here if any],
          ]
       }

     var baseURL: URL {
        
         return  URL(string:"https:www.currency.com")
     }

    var path: String {
       switch self {

         case .exchangeRate:

          return "/exchangeRate"
        }
     }

    var method: Moya.Method {
       switch self {

          case .exchangeRate:

           return .post
        }
     }

    var parameters: Data? {
        switch self {

          case let .exchangeRate(param):

           return try! param.serializedData()
        }
      }

   var task: Task {
        switch self {

           case .exchangeRate:

            return .requestData(self.parameters!)    
         }
       }
    }

You can access an API like this:

     provider = MoyaProvider<GitHub>()
     provider.request(.exchangeRate(param:[here will be protobuf model object])) {                
          result in
         switch result {
            case let .success(moyaResponse):
              //do something with the response data
            case let .failure(error):
              //error occured
            }
       }