简体   繁体   English

iOS 网络 - Moya 和协议缓冲区序列化

[英]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?谁能详细说明使用 Moya 与使用 ProtoBuf 序列化而不是 JSON 表示法的 web 服务进行通信的可能性? 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.这是如何将 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!)    
         }
       }
    }

You can access an API like this:您可以像这样访问 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
            }
       }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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