1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 3 years have passed since last update.

(Swift)ProtocolBuffersのレスポンスをJSONでコンソールに表示する

Posted at

取り急ぎコンソールにprintしたい時のための。

Dataのextensionを定義

Data
// MARK: - Data
private extension Data {
    
    // DummyやStub用のJSONファイル作成に使用する
    var prettyJson: String? {
        guard let object = try? JSONSerialization.jsonObject(with: self, options: []),
              let data = try? JSONSerialization.data(withJSONObject: object, options: [.prettyPrinted]),
              let prettyPrintedString = String(data: data, encoding:.utf8) else {
            return nil
        }

        return prettyPrintedString
    }
}

API通信箇所で呼び出す関数を定義

API
// MARK: - Private
extension APIDataStoreImpl {
    
    /// JSONを整えてコンソールに表示する
    private func printPrettyJson(_ result: Proto_Response) {
        if let object = try? result.jsonUTF8Data() {
            print("jsonString:\n\(object.prettyJson ?? "nil")")
        }
    }
}

呼び出し

通信成功時にresponseを渡すだけで、
結果がいい感じに改行された状態で表示されます

1
1
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
1
1

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?