Data+Cache.swift 851 B

1234567891011121314151617181920212223242526272829
  1. //
  2. // Data+Cache.swift
  3. // SwiftBilibili
  4. //
  5. // Created by 罗文 on 2021/1/22.
  6. // Copyright © 2021年 罗文. All rights reserved.
  7. //
  8. import ObjectMapper
  9. import SwiftyJSON
  10. extension Data {
  11. func cacheObject<T: ImmutableMappable>(_ type: T.Type) -> T {
  12. let json = try! JSON(data: self)
  13. let data = json[RESULT_DATA].dictionaryObject
  14. return try! Mapper<T>().map(JSON: data!)
  15. }
  16. func cacheArray<T: ImmutableMappable>(_ type: T.Type) -> [T] {
  17. let jsonArray = try! JSON(data: self).arrayObject
  18. let data = try! JSONSerialization.data(withJSONObject: jsonArray!, options: JSONSerialization.WritingOptions.prettyPrinted)
  19. let jsonString = String(data: data, encoding: String.Encoding.utf8)!
  20. return try! Mapper<T>().mapArray(JSONString: jsonString)
  21. }
  22. }