简体   繁体   中英

iOS Networking - Moya & Protocol Buffer Serialisation

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:)

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
            }
       }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM