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()
}
}
Cod: Selectaţi tot
//Constants.swift
import Foundation
struct Constants {
//SQLite
static let dbPath = "/Users/admin/Desktop/forex.sqlite3"
}
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)
}
}
}
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"]
}
}
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()
Autor thread: stefanciprian, Echipa Specialişti IT
Mulțumesc