How to make GMSPlace Codable? - ios

anyone idea about to make GSMPlace as codable from googleplaces?
what I want is, store GMSPlace data(place and name) into UserDefaults and then retrieve from UserDefaults and store back to destinationPlace.
import Foundation
import RxSwift
import RxCocoa
import GooglePlaces
class SearchViewModel {
var destinationPlace: BehaviorRelay<GMSPlace?> = BehaviorRelay(value: nil)
var isValid: Bool {
if destinationPlace.value != nil {
return true
}
return false
}
}

I don't know any of the specifics of GooglePlaces or the object type GMSPlace.
But in Swift if you want to add something to a class you can create an extension, optionally add protocols to it and add functions. In your case it would look something like this:
extension GMSPlace: Codable {
enum CodingKeys: String, CodingKey {
case propertyName1
case propertyName2
...
}
public init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
propertyName1 = try container.decode(String.self, forKey: .propertyName1)
propertyName2 = try container.decode(Int.self, forKey: .propertyName2)
}
public func encode(to encoder: Encoder) throws {
var container = encoder.container(keyedBy: CodingKeys.self)
try container.encode(propertyName1, forKey: .propertyName1)
try container.encode(propertyName2, forKey: .propertyName2)
}
}
You will have to figure out the specifics of what properties you need to include, what types they need to map to etc.
You should also open a ticket for them somewhere to add this to the SDK themselves if its causing an issue for you

Related

Getting document ID when decoding firestore document using Swift Codable

I'm using a class to decode retrieved firestore documents, and it works as expected if I don't want to manipulate the data:
class Room: Identifiable, Codable {
#DocumentID public var id:String?
var name:String
}
However if I try to use my own init to set values, I can't get the firestore document ID?
class Room: Identifiable, Codable {
#DocumentID public var id:String?
var name:String
enum Keys:String, CodingKey {
case name
case capacity
case photo = "url"
}
required init(from decoder: Decoder) throws {
// How do I get the document ID to set the id value?
let container = try decoder.container(keyedBy: Keys.self)
name = try container.decode(String.self, forKey: .name)
capacity = try container.decode(Int.self, forKey: .capacity)
photo = try container.decode(String.self, forKey: .photo)
// Do some more stuff here...
}
}
Found the answer elsewhere, and this works perfectly. Posting for anyone else who arrives here with the same query.
TL;DR -
Use the following to decode the DocumentReference in your init function:
ref = try container.decode(DocumentID<DocumentReference>.self, forKey: .ref)
.wrappedValue
Longer explanation:
I won't pretend to understand this 100%, but there's a good explanation here https://github.com/firebase/firebase-ios-sdk/issues/7242

How to Decode selected keys manually and rest with the automatic decoding with swift Decodable?

Here is the code I am using,
struct CreatePostResponseModel : Codable{
var transcodeId:String?
var id:String = ""
enum TopLevelCodingKeys: String, CodingKey {
case _transcode = "_transcode"
case _transcoder = "_transcoder"
}
enum CodingKeys:String, CodingKey{
case id = "_id"
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: TopLevelCodingKeys.self)
if let transcodeId = try container.decodeIfPresent(String.self, forKey: ._transcode) {
self.transcodeId = transcodeId
}else if let transcodeId = try container.decodeIfPresent(String.self, forKey: ._transcoder) {
self.transcodeId = transcodeId
}
}
}
Here, transcodeId is decided by either _transcode or _transcoder.
But I want id and rest of the keys (not included here) to be automatically decoded. How can I do it ?
You need to manually parse all the keys once you implement init(from:) in the Codable type.
struct CreatePostResponseModel: Decodable {
var transcodeId: String?
var id: String
enum CodingKeys:String, CodingKey{
case id, transcode, transcoder
}
init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
id = try container.decodeIfPresent(String.self, forKey: .id) ?? ""
if let transcodeId = try container.decodeIfPresent(String.self, forKey: .transcode) {
self.transcodeId = transcodeId
} else if let transcodeId = try container.decodeIfPresent(String.self, forKey: .transcoder) {
self.transcodeId = transcodeId
}
}
}
In the above code,
In case you only want to decode the JSON, there is no need to use Codable. Using Decodable is enough.
Using multiple enums for CodingKey seems unnecessary here. You can use a single enum CodingKeys.
If the property name and the key name is an exact match, there is no need to explicitly specify the rawValue of that case in enum CodingKeys. So, there is no requirement of "_transcode" and "_transcoder" rawValues in TopLevelCodingKeys.
Apart from all that, you can use keyDecodingStrategy as .convertFromSnakeCase to handle underscore notation (snake case notation), i.e.
do {
let decoder = JSONDecoder()
decoder.keyDecodingStrategy = .convertFromSnakeCase //here.....
let model = try decoder.decode(CreatePostResponseModel.self, from: data)
print(model)
} catch {
print(error)
}
So, you don't need to explicitly handle all the snake-case keys. It'll be handled by the JSONDecoder on its own.
This can be one of the good solution for you wherever you want you can add multiple keys for one variable:
var transcodeId:String?
public init(from decoder: Decoder) throws {
do {
let container = try decoder.container(keyedBy: CodingKeys.self)
transcodeId = container.getValueFromAvailableKey(codingKeys: [CodingKeys._transcoder,CodingKeys._transcode])
} catch {
print("Error reading config file: \(error.localizedDescription)")
}
}
extension KeyedDecodingContainerProtocol{
func getValueFromAvailableKey(codingKeys:[CodingKey])-> String?{
for key in codingKeys{
for keyPath in self.allKeys{
if key.stringValue == keyPath.stringValue{
do{
return try self.decodeIfPresent(String.self, forKey: keyPath)
} catch {
return nil
}
}
}
}
return nil
}
}
Hope it helps.
The compiler-generated init(from:) is all-or-nothing. You can’t have it decode some keys and “manually” decode others.
One way to use the compiler-generated init(from:) is by giving your struct both of the possible encoded properties, and make transcodeId a computed property:
struct CreatePostResponseModel: Codable {
var transcodeId: String? {
get { _transcode ?? _transcoder }
set { _transcode = newValue; _transcoder = nil }
}
var _transcode: String? = nil
var _transcoder: String? = nil
var id: String = “”
// other properties
}

Add default field to Swift Decodable object [duplicate]

Swift 4 added the new Codable protocol. When I use JSONDecoder it seems to require all the non-optional properties of my Codable class to have keys in the JSON or it throws an error.
Making every property of my class optional seems like an unnecessary hassle since what I really want is to use the value in the json or a default value. (I don't want the property to be nil.)
Is there a way to do this?
class MyCodable: Codable {
var name: String = "Default Appleseed"
}
func load(input: String) {
do {
if let data = input.data(using: .utf8) {
let result = try JSONDecoder().decode(MyCodable.self, from: data)
print("name: \(result.name)")
}
} catch {
print("error: \(error)")
// `Error message: "Key not found when expecting non-optional type
// String for coding key \"name\""`
}
}
let goodInput = "{\"name\": \"Jonny Appleseed\" }"
let badInput = "{}"
load(input: goodInput) // works, `name` is Jonny Applessed
load(input: badInput) // breaks, `name` required since property is non-optional
You can implement the init(from decoder: Decoder) method in your type instead of using the default implementation:
class MyCodable: Codable {
var name: String = "Default Appleseed"
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let name = try container.decodeIfPresent(String.self, forKey: .name) {
self.name = name
}
}
}
You can also make name a constant property (if you want to):
class MyCodable: Codable {
let name: String
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
if let name = try container.decodeIfPresent(String.self, forKey: .name) {
self.name = name
} else {
self.name = "Default Appleseed"
}
}
}
or
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Default Appleseed"
}
Re your comment: With a custom extension
extension KeyedDecodingContainer {
func decodeWrapper<T>(key: K, defaultValue: T) throws -> T
where T : Decodable {
return try decodeIfPresent(T.self, forKey: key) ?? defaultValue
}
}
you could implement the init method as
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
self.name = try container.decodeWrapper(key: .name, defaultValue: "Default Appleseed")
}
but that is not much shorter than
self.name = try container.decodeIfPresent(String.self, forKey: .name) ?? "Default Appleseed"
You can use a computed property that defaults to the desired value if the JSON key is not found.
class MyCodable: Decodable {
var name: String { return _name ?? "Default Appleseed" }
var age: Int?
// this is the property that gets actually decoded/encoded
private var _name: String?
enum CodingKeys: String, CodingKey {
case _name = "name"
case age
}
}
If you want to have the property read-write, you can also implement the setter:
var name: String {
get { _name ?? "Default Appleseed" }
set { _name = newValue }
}
This adds a little extra verbosity as you'll need to declare another property, and will require adding the CodingKeys enum (if not already there). The advantage is that you don't need to write custom decoding/encoding code, which can become tedious at some point.
Note that this solution only works if the value for the JSON key either holds a string or is not present. If the JSON might have the value under another form (e.g. it's an int), then you can try this solution.
Approach that I prefer is using so called DTOs - data transfer object.
It is a struct, that conforms to Codable and represents the desired object.
struct MyClassDTO: Codable {
let items: [String]?
let otherVar: Int?
}
Then you simply init the object that you want to use in the app with that DTO.
class MyClass {
let items: [String]
var otherVar = 3
init(_ dto: MyClassDTO) {
items = dto.items ?? [String]()
otherVar = dto.otherVar ?? 3
}
var dto: MyClassDTO {
return MyClassDTO(items: items, otherVar: otherVar)
}
}
This approach is also good since you can rename and change final object however you wish to.
It is clear and requires less code than manual decoding.
Moreover, with this approach you can separate networking layer from other app.
You can implement.
struct Source : Codable {
let id : String?
let name : String?
enum CodingKeys: String, CodingKey {
case id = "id"
case name = "name"
}
init(from decoder: Decoder) throws {
let values = try decoder.container(keyedBy: CodingKeys.self)
id = try values.decodeIfPresent(String.self, forKey: .id) ?? ""
name = try values.decodeIfPresent(String.self, forKey: .name)
}
}
I came across this question looking for the exact same thing. The answers I found were not very satisfying even though I was afraid that the solutions here would be the only option.
In my case, creating a custom decoder would require a ton of boilerplate that would be hard to maintain so I kept searching for other answers.
I ran into this article that shows an interesting way to overcome this in simple cases using a #propertyWrapper. The most important thing for me, was that it was reusable and required minimal refactoring of existing code.
The article assumes a case where you'd want a missing boolean property to default to false without failing but also shows other different variants.
You can read it in more detail but I'll show what I did for my use case.
In my case, I had an array that I wanted to be initialized as empty if the key was missing.
So, I declared the following #propertyWrapper and additional extensions:
#propertyWrapper
struct DefaultEmptyArray<T:Codable> {
var wrappedValue: [T] = []
}
//codable extension to encode/decode the wrapped value
extension DefaultEmptyArray: Codable {
func encode(to encoder: Encoder) throws {
try wrappedValue.encode(to: encoder)
}
init(from decoder: Decoder) throws {
let container = try decoder.singleValueContainer()
wrappedValue = try container.decode([T].self)
}
}
extension KeyedDecodingContainer {
func decode<T:Decodable>(_ type: DefaultEmptyArray<T>.Type,
forKey key: Key) throws -> DefaultEmptyArray<T> {
try decodeIfPresent(type, forKey: key) ?? .init()
}
}
The advantage of this method is that you can easily overcome the issue in existing code by simply adding the #propertyWrapper to the property. In my case:
#DefaultEmptyArray var items: [String] = []
Hope this helps someone dealing with the same issue.
UPDATE:
After posting this answer while continuing to look into the matter I found this other article but most importantly the respective library that contains some common easy to use #propertyWrappers for these kind of cases:
https://github.com/marksands/BetterCodable
If you don't want to implement your encoding and decoding methods, there is somewhat dirty solution around default values.
You can declare your new field as implicitly unwrapped optional and check if it's nil after decoding and set a default value.
I tested this only with PropertyListEncoder, but I think JSONDecoder works the same way.
If you think that writing your own version of init(from decoder: Decoder) is overwhelming, I would advice you to implement a method which will check the input before sending it to decoder. That way you'll have a place where you can check for fields absence and set your own default values.
For example:
final class CodableModel: Codable
{
static func customDecode(_ obj: [String: Any]) -> CodableModel?
{
var validatedDict = obj
let someField = validatedDict[CodingKeys.someField.stringValue] ?? false
validatedDict[CodingKeys.someField.stringValue] = someField
guard
let data = try? JSONSerialization.data(withJSONObject: validatedDict, options: .prettyPrinted),
let model = try? CodableModel.decoder.decode(CodableModel.self, from: data) else {
return nil
}
return model
}
//your coding keys, properties, etc.
}
And in order to init an object from json, instead of:
do {
let data = try JSONSerialization.data(withJSONObject: json, options: .prettyPrinted)
let model = try CodableModel.decoder.decode(CodableModel.self, from: data)
} catch {
assertionFailure(error.localizedDescription)
}
Init will look like this:
if let vuvVideoFile = PublicVideoFile.customDecode($0) {
videos.append(vuvVideoFile)
}
In this particular situation I prefer to deal with optionals but if you have a different opinion, you can make your customDecode(:) method throwable

How to store Big Integer in Swift 4 Codable?

I am trying auto parsing an API with swift 4 codable. Some of the fields in the API are big integer which Codable does not support nor Swift 4.NSNumber is not supported by Codable and UInt64 is small for it to fit. I tried with a thrid party library and made my variable within the codable to that type,but that also did not work. I tried to to make a custom class or struct which will do the conversion with only one value in container but don't know how to make the container accept Big Int type or convert it to string.
My code is below like this. Is there any solution to it?
import Foundation
import BigNumber
class PersonalizationLean:Codable {
var hubId:String?
var appId:UInt8?
var nodeId:Int?
var name:String?
var ico:String?
var icoBase64:String?
var isBin:Bool?
var lastModifiedAt:Int?
var shouldShowInUi:Bool?
var applianceType:String?
var tags:[String]?
var placeId:PlaceIdCodable?
var roomId:String?
var id:String?
var key:String?
enum CodingKeys:String,CodingKey {
case hubId
case appId
case nodeId
case name
case ico
case icoBase64
case isBin
case lastModifiedAt
case shouldShowInUi
case applianceType
case tags
case placeId
case roomId
case id
case key
}
// required init(from decoder: Decoder) throws {
// do {
// let container = try decoder.container(keyedBy: CodingKeys.self)
// self.hubId = try container.decode(String.self, forKey: .hubId)
// self.appId = try container.decode(UInt8.self, forKey: .appId)
// self.nodeId = try container.decode(Int.self, forKey: .nodeId)
// self.name = try container.decode(String.self, forKey: .name)
// self.ico = try container.decode(String.self, forKey: .ico)
// self.icoBase64 = try container.decode(String.self, forKey: .icoBase64)
// self.isBin = try container.decode(Bool.self, forKey: .isBin)
// self.lastModifiedAt = try container.decode(Int.self, forKey: .lastModifiedAt)
// self.shouldShowInUi = try container.decode(Bool.self, forKey: .shouldShowInUi)
// self.applianceType = try container.decode(String.self,forKey: .applianceType)
// self.tags = try container.decode([String].self,forKey: .tags)
//
//
// }catch {
// print(error)
// }
// }
}
class PlaceIdCodable:Codable {
var placeId:String?
required init(from decoder:Decoder) throws {
do {
let container = try decoder.singleValueContainer()
let placeIdBig = try container.decode(BInt.self) //this gives error
}catch {
print(error)
}
}
}
The library I am using is BigNumber
Use built-in Decimal which derives from NSDecimalNumber. It adopts Codable
BInt do not conform to Codable OR Decodable
to use it here it should confirm to mentioned protocol
extension BInt: Decodable {
public init(from decoder: Decoder) throws {
// Initialization goes here
}
}

Ignoring superclass property while decoding subclass

I'm trying to make inherited data model in order to parse it with JSONDecoder.
class FirstClass : Codable {
let firstClassProperty: Int
final let arrayOfInts: [Int]
}
class SecondClass : FirstClass {
let secondClassProperty1: Int
let secondClassProperty2: Int
private enum CodingKeys : String, CodingKey {
case secondClassProperty1, secondClassProperty2
}
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
secondClassProperty1 = try container.decode(Int.self, forKey: .secondClassProperty1)
secondClassProperty2 = try container.decode(Int.self, forKey: .secondClassProperty2)
try super.init(from: decoder)
}
}
I use this JSON for FirstClass:
{
"firstClassProperty": 123,
"arrayOfInts": [
123
]
}
and this for SecondClass:
{
"firstClassProperty": {},
"secondClassProperty1": {},
"secondClassProperty2": {}
}
How can I get rid of arrayOfInts in my subclass but let it be in superclass if keyword final doesn't work in this case?
Here's Playground. Thanks for your answers!
A quick hack is to declare it as optional. For instance:
class FirstClas: Codable {
let firstClassProperty: Int
final let arrayOfInts: [Int]?
}
That would work around a missing arrayOfInts automatically.
Manual solution. Another solution is to implement the Decodable protocol yourself — as you did in SecondClass — and decode arrayOfInts using decodeIfPresent (and use a default value otherwise).
Superclass decoding. By the way, the recommended way to forward the Decoder to the superclass is by using superDecoder() method:
...
let superDecoder = try container.superDecoder()
try super.init(from: superDecoder)
You can use like this :
class FirstClass : Codable {
let firstClassProperty: Int
final let arrayOfInts: [Int]?
required init(from decoder: Decoder) throws {
let container = try decoder.container(keyedBy: CodingKeys.self)
firstClassProperty = try container.decode(Int.self, forKey: .firstClassProperty)
arrayOfInts = try container.decodeIfPresent([Int].self, forKey: .arrayOfInts)
}
}

Resources