首页 > 解决方案 > iOS 网络 - Moya 和协议缓冲区序列化

问题描述

谁能详细说明使用 Moya 与使用 ProtoBuf 序列化而不是 JSON 表示法的 Web 服务进行通信的可能性?可能吗?它是否已经实现或是否有任何扩展?任何信息都非常感谢:)

标签: iosjsonswiftprotocol-buffersmoya

解决方案


对的,这是可能的

这是如何将 protobuf 与 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!)    
         }
       }
    }

您可以像这样访问 API:

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

推荐阅读