Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Store and Fetch an array #188

Closed
sylvan-d-ash opened this issue Jun 7, 2018 · 5 comments
Closed

Store and Fetch an array #188

sylvan-d-ash opened this issue Jun 7, 2018 · 5 comments

Comments

@sylvan-d-ash
Copy link

sylvan-d-ash commented Jun 7, 2018

I would like to know how to store and subsequently fetch an array. I've got the following models:

struct World: Codable {
    var regions: [Region]
}

struct Region: Codable {
    var name: String
    var numberOfCountries: Int
    
    /// specify the keys in the JSON from the API
    private enum CodingKeys: String, CodingKey {
        case name = "regionName"
        case numberOfCountries = "nrCountries"
    }
    
    public init(from decoder: Decoder) throws {
        let values = try decoder.container(keyedBy: CodingKeys.self)
        let number = try values.decode(String.self, forKey: .numberOfCountries)
        
        numberOfCountries = Int(number) ?? 0
        name = try values.decode(String.self, forKey: .name)
    }
}

I'm saving the World info like:

let regions = [Region(name: "Europe", numberOfCountries: 21), Region(name: "Asia", numberOfCountries: 54)]
let world = World(regions: regions)
try self.storage?.setObject(world, forKey: "Constants.World")

And trying to fetch this data later on like:

do {
    let world = try storage.object(ofType: World.self, forKey: "Constants.World")
} catch {
    print("\(error.localizedDescription)")
}

The saving seems to work OK, but I get the following error whenever I try to fetch the data from the cache: The data couldn’t be read because it isn’t in the correct format.

Any idea what I could be doing wrong? Or how should I save the above data?

@onmyway133
Copy link
Contributor

onmyway133 commented Jun 7, 2018

@sylvan-d-ash Hi, when you load, can you try

let world = try storage.object(ofType: [World].self, forKey: "Constants.World")

Basically, use [World].self instead of World.self. Also you save as [Region] but you load with World?

@markhao-cb
Copy link

Hi @sylvan-d-ash! Did you figure out what went wrong?

@sylvan-d-ash
Copy link
Author

@MarkHao yes, I did. I should have commented about it here, because I now don't remember the problem clearly, but it had to do with the numberOfCountries being an int. I resolved it by changing it to a string.

I'm guessing that adding an encode function to deal with the int value would be another way to resolve it...but not sure about this.

@bhanuMatta
Copy link

@onmyway133 ,@sylvan-d-ash - Can you show how you created the Storage initializer function. When we are creating the Storage class init method it also asks for Transformer type.

let diskConfig = DiskConfig(
name: "GatherCache",
expiry: .date(Date().addingTimeInterval(2*86400)),
maxSize: 1000000 * 50,
directory: try! FileManager.default.url(for: .documentDirectory, in: .userDomainMask,
appropriateFor: nil, create: true).appendingPathComponent("MyPreferences"),
protectionType: .complete
)

    let memoryConfig = MemoryConfig(
        expiry: .date(Date().addingTimeInterval(2*60)),
        countLimit: 50,
        totalCostLimit: 50
    )
    
  let storage = try? Storage(
      diskConfig: diskConfig,
      memoryConfig: memoryConfig,
      transformer: TransformerFactory.forCodable(ofType: User.self) // Storage<User>
    )

Here my User is. -
struct User : Codable {
let firstName: String
let lastName: String

enum CodingKeys: String, CodingKey {
    case firstName = "first_name"
    case lastName = "last_name"
}

}

But what i want to achieve is that , i want to cache a array of [User] . How do i do that , do I need to change my Storage init method .

@3lvis
Copy link
Collaborator

3lvis commented Oct 4, 2020

Hi @bhanuMatta, sorry for the late reply, where you able to resolve your issue?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

5 participants