Created
December 27, 2017 19:35
-
-
Save kmkrn/debd767c138a3bcd7563b7e4d9171b46 to your computer and use it in GitHub Desktop.
Realm + Codable. Serializer example (version 1)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import Foundation | |
import RealmSwift | |
class JSONSerializer { | |
func serialize(input sourceName: String) { | |
let path = Bundle.main.path(forResource: sourceName, ofType: nil) | |
let url = URL(fileURLWithPath: path!) | |
let jsonDecoder = JSONDecoder() | |
do { | |
let data = try Data(contentsOf: url) | |
let json = try JSONSerialization.jsonObject(with: data, options: .allowFragments) | |
guard json is [AnyObject] else { | |
assert(false, "failed to parse") | |
return | |
} | |
do { | |
let cats = try jsonDecoder.decode([Cat].self, from: data) | |
let realm = try! Realm() | |
for cat in cats { | |
try! realm.write { | |
realm.add(cat) | |
} | |
} | |
} catch { | |
print("failed to convert data") | |
} | |
} catch let error { | |
print(error) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment