Upgrade to Pro — share decks privately, control downloads, hide ads and more …

protocol_buffers.pdf

Kyohei Ito
November 20, 2016
6.2k

 protocol_buffers.pdf

Kyohei Ito

November 20, 2016
Tweet

Transcript

  1. "I guess Apple decided that JSON is a relic of

    the past along with Objective-C" - @cjwirth
  2. .protoͰఆٛͰ͖Δجຊͷܕ3 int32 sint32 sfixed32 uint32 fixed32 int64 sint64 sfixed64 uint64

    fixed64 bool float double string bytes 3 apple/swift-protobufͷAPI OverviewΑΓൈਮ
  3. DataModel.proto syntax = "proto3"; message BookInfo { int64 id =

    1; string title = 2; string author = 3; } message MyLibrary { int64 id = 1; string name = 2; repeated BookInfo books = 3; map<string,string> keys = 4; } quick-example
  4. Field Types int64 id = 1; string title = 2;

    string author = 3; • ܕͱม਺໊Λઃఆ͢Δ
  5. Tags int64 id = 1; string title = 2; string

    author = 3; • message಺ͰҰҙͷ਺஋ΛׂΓ౰ͯΔ • ॱং͸ߟྀ͠ͳͯ͘΋ྑ͍
  6. ΋͏Ұ౓DataModel.proto syntax = "proto3"; message BookInfo { int64 id =

    1; string title = 2; string author = 3; } message MyLibrary { int64 id = 1; string name = 2; repeated BookInfo books = 3; map<string,string> keys = 4; }
  7. ϥΠϒϥϦͷ௥Ճ • Package Manager dependencies: [ .Package(url: "https://github.com/apple/swift-protobuf.git", Version(0,9,24)) ]

    • CocoaPods pod 'SwiftProtobuf', git: 'https://github.com/apple/swift-protobuf.git', :tag => '0.9.24' ※ϓϥάΠϯΛ࡞੒ͨ࣌͠ͷtagͱΠϯετʔϧόʔδϣϯΛ߹ Θ͍ͤͯͩ͘͞ɻ
  8. Binary serializable γϦΞϥΠζ let library = MyLibrary() let data =

    try library.serializeProtobuf() σγϦΞϥΠζ let library = try MyLibrary(protobuf: data)
  9. JSON serializable γϦΞϥΠζ let library = MyLibrary() let json =

    try library.serializeJSON() σγϦΞϥΠζ let json = String(bytes: data, encoding: String.Encoding.utf8)! let library = try MyLibrary(json: json)
  10. JSON request let url = URL(string: "http://localhost:8080/")! var request =

    URLRequest(url: url) let value = "application/json" request.setValue(value, forHTTPHeaderField: "Accept")
  11. protobuf request let url = URL(string: "http://localhost:8080/")! var request =

    URLRequest(url: url) let value = "application/protobuf" request.setValue(value, forHTTPHeaderField: "Accept")
  12. response let library = MyLibrary() let accept = request.headers["Accept"] if

    accept == "application/protobuf" { response.headers["Content-Type"] = "application/protobuf" response.send(data: try library.serializeProtobuf()) } else { response.headers["Content-Type"] = "application/json; charset=UTF-8" response.send(try library.serializeJSON()) }