Swift - Exemplu Database SQLite, Model & Mapper

Xcode și Swift Code sunt limbaje de programare folosite pentru dezvoltarea aplicațiilor de MacOS, iOS, watchOS și tvOS. Afla cum poți implementa cod.
Avatar utilizator
specialist it
Mesaje: 205
Membru din: 28 Iun 2017, 16:39
6
Contact:

Swift - Exemplu Database SQLite, Model & Mapper

Mesaj de specialist it »

Salut,

Mai jos regăsiți un exemplu de cod folosind o clasă de tip Database pe care îl puteți integra în cadrul unui proiect mai mic:

Cod: Selectaţi tot

//DataBase.swift

import Foundation
import SQLite

class DataBase {
    // 
    static let conn = try! Connection(Constants.dbPath)

    struct Entries {
        static let entries = Table("entries")
        static let id = Expression<Int64>("id")
        static let base = Expression<String?>("base")
        static let date = Expression<String?>("date")
        static let rateSymbol = Expression<String?>("rate_symbol")
        static let rateValue = Expression<String?>("rate_value")
        
        static func createIfNotExists() {
            do {
                try DataBase.conn.run(entries.create(ifNotExists: true){ t in
                    t.column(id, primaryKey: true)
                    t.column(base)
                    t.column(date)
                    t.column(rateSymbol)
                    t.column(rateValue)
                })
            }catch {
                print(error)
            }
        }
    }
    
    init() {
        Entries.createIfNotExists()
    }
}
De asemenea clasa Database are nevoie de un struct Constants definit mai jos:

Cod: Selectaţi tot

//Constants.swift

import Foundation

struct Constants {
    //SQLite
    static let dbPath = "/Users/admin/Desktop/forex.sqlite3"
}
Următorul pas constă în crearea unui Model care are sa aibă acces la Database:

Cod: Selectaţi tot

//ForexModel.swift

import Foundation
import SQLite

class ForexModel {
    var base: String?
    var date: String?
    var rate_symbol: String?
    var rate_value: String?
    
    init(f: ForexMapper) {
        self.base = f.base
        self.date = f.date
        
        for (key, value) in f.rates {
            self.rate_symbol = key
            self.rate_value = "\(value)"
        }
    }
    
    func create() {
        let insert = DataBase.Entries.entries.insert(
            DataBase.Entries.base <- self.base,
            DataBase.Entries.date <- self.date,
            DataBase.Entries.rateSymbol <- self.rate_symbol,
            DataBase.Entries.rateValue <- self.rate_value
        )
        do {
            try DataBase.conn.run(insert)
        } catch {
            print(error)
        }
    }
}
Urmează construcția Mapper-ului care va fi folosit pentru a mapa un string JSON și îl va transmite Model-ului prezentat anterior:

Cod: Selectaţi tot

//ForexMapper.swift

import Foundation
import ObjectMapper

class ForexMapper: Mappable {
    var base: String?
    var date: String?
    var rates: [String : AnyObject] = [:]
    
    required init?(map: Map) {
    
    }
    
    func mapping(map: Map) {
        base <- map["base"]
        date <- map["date"]
        rates <- map["rates"]
    }
}
In final vom beneficia de codul scris mai sus astfel:

Cod: Selectaţi tot

//Parse JSON received from API call to string  
            let convertedString = String(data: response, encoding: String.Encoding.utf8) 
            
            //map JSON using the Mapper
            let f = ForexMapper(JSONString: convertedString!) 
            
            //pass Mapper obj to Model
            let entry = ForexModel(f: f!) 
            entry.create()
Sper că veți găsi util acest thread. Pentru întrebări, vă stăm la dispoziție.

Autor thread: stefanciprian, Echipa Specialişti IT

Mulțumesc
Moderator și Specialist IT
Scrie răspuns