Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to save data in swift 4 with codable and file manager

Tags:

swift4

codable

hi every ones there anyone know how to save data in swift 4 i made a emoji app that i can describe the emojis and i have a future that i can save the new emoji in the app i wrote this code in my emoji class but as i want return the emoji i get an error please help me .

import Foundation

struct Emoji : Codable {
    var symbol : String
    var name : String
    var description : String
    var usage : String
    static let documentsdirectory = FileManager.default.urls(for: .documentDirectory, in: .userDomainMask).first!
    static let archiveurl = documentsdirectory.appendingPathComponent("emojis").appendingPathExtension("plist")

    static func SaveToFile (emojis: [Emoji]) {
        let propetyencod = PropertyListEncoder()
        let encodemoj = try? propetyencod.encode(emojis)
        try? encodemoj?.write(to : archiveurl , options : .noFileProtection)
    }
    static func loadeFromFile () -> [Emoji] {
    let propetydicod = PropertyListDecoder()
        if let retrivdate = try? Data(contentsOf: archiveurl),
        let decodemoj = try?
            propetydicod.decode(Array<Emoji>.self, from: retrivdate){

        }
        return decodemoj        in this line i get error
    }

}
like image 735
user8058965 Avatar asked Oct 17 '22 05:10

user8058965


1 Answers

The error occurs because decodemoj is out of scope. You need to write

static func loadeFromFile() -> [Emoji] {
    let propetydicod = PropertyListDecoder()
    if let retrivdate = try? Data(contentsOf: archiveurl),
       let decodemoj = try? propetydicod.decode(Array<Emoji>.self, from: retrivdate) {
         return decodemoj
    }
    return [Emoji]()
}

and return an empty array in case of an error. Alternatively declare the return value as optional array and return nil.


But why not a do - catch block?

static func loadeFromFile() -> [Emoji] {
   let propetydicod = PropertyListDecoder()
   do {
      let retrivdate = try Data(contentsOf: archiveurl)
      return try propetydicod.decode([Emoji].self, from: retrivdate)
   } catch {
     print(error)
     return [Emoji]()
   }
}
like image 105
vadian Avatar answered Oct 21 '22 07:10

vadian