-1

when a user login, I get an answer from server that contains an array like this:

{"answer":{"id":26,"username":"iosuser","address":"iosios","phone_number":"123123123","email":"gmail@gmail.com","created_at":"2019-02-02 12:42:50","updated_at":"2019-02-02 21:40:29","provider_id":"1","is_loged_in":1,"user_id":"24","user_type":1}}

How to save this array's data in userdefaults and use it later for example in a profile page?

Any help much appreciated.

Eric Aya
  • 69,473
  • 35
  • 181
  • 253
Jessica Kimble
  • 493
  • 2
  • 7
  • 17
  • 1
    do not save any user info in userdefault. Better look at given answer OR you can create a class/struct these info. – Gagan_iOS Feb 02 '19 at 21:58

1 Answers1

3

First don't recommend saving it in userDefault , you can use coredata / realm , and your content is a dictionary that contains an array , but you can do

struct Root: Codable {
    let answer: Answer
}

struct Answer: Codable {
    let id: Int
    let username, address, phoneNumber, email: String
    let createdAt, updatedAt, providerID: String
    let isLogedIn: Int
    let userID: String
    let userType: Int

    enum CodingKeys: String, CodingKey {
        case id, username, address
        case phoneNumber = "phone_number"
        case email
        case createdAt = "created_at"
        case updatedAt = "updated_at"
        case providerID = "provider_id"
        case isLogedIn = "is_loged_in"
        case userID = "user_id"
        case userType = "user_type"
    }
}


UserDefaults.standard.set(data,forKey:"AnyKey")

then read the data and

let res = try? JSONDecoder().decode(Root.self,from:data)

if you need to strip the array only then

do {
  let tr = try JSONSerialization.jsonObject(with:data) as! [String:Any]
  let arr = tr["answer"] as! [Any]
  let ansData = try JSONSerialization.data(withJSONObject:arr, options:[]) 
  UserDefaults.standard.set(ansData,forKey:"AnyKey")
} catch { print(error) }

After that read it like

 guard let data = UserDefaults.standard.data(forKey:"AnyKey") else { return }
 let res = try? JSONDecoder().decode([Answer].self,from:data)
Shehata Gamal
  • 98,760
  • 8
  • 65
  • 87