Zhan Zhan - 1 month ago 14
iOS Question

How to write JSON to Realm in Swift

I can't find information how to write my

JSON
data to my
Realm DB
in
Swift
.

I have class:

class News: Object {
dynamic var newsID: String = ""
dynamic var newsTitle: String = ""
dynamic var newsFullText: String = ""
dynamic var newsAutor: String = ""
dynamic var newsCommentCount: String = ""
dynamic var newsSeenCount: String = ""
dynamic var newsDate: String = ""
dynamic var newsCategory: String = ""
}


In here I take
JSON
from server:

func parseJSONData(data: NSData) -> [News] {

do {
let temp: NSString = NSString(data: data, encoding: NSUTF8StringEncoding)!
let myNSData = temp.dataUsingEncoding(NSUTF8StringEncoding)!

let jsonResult = try NSJSONSerialization.JSONObjectWithData(myNSData, options: NSJSONReadingOptions.MutableContainers) as! NSDictionary
let jsonNews = jsonResult["posts"] as! [AnyObject]
for jsonnewes in jsonNews {
let newsJson = News()
newsJson.newsTitle = jsonnewes["post_title"] as! String
newsJson.newsAutor = jsonnewes["author_name"] as! String
newsJson.newsFullText = jsonnewes["full_text"] as! String
newsJson.newsID = jsonnewes["id"] as! String
newsJson.newsCategory = jsonnewes["menu_category_name"] as! String
newsJson.newsDate = jsonnewes["create_date"] as! String
newsJson.newsSeenCount = jsonnewes["review"] as! String
newsJson.newsCommentCount = jsonnewes["comment_count"] as! String
newsItems.append(newsJson)
}
} catch {
print(error)
}
return newsItems
}


And how to write my data to
Realm DB
?

Answer

this :

func insertOrUpdate(news: News) {
    try! realm.write({
            realm.add(news)
        })
}

but it is better you create a model without inherit from object :

class News {
   var newsID: String = ""
   var newsTitle: String = ""
   var newsFullText: String = ""
   var newsAutor: String = ""
   var newsCommentCount: String = ""
   var newsSeenCount: String = ""
   var newsDate: String = ""
   var newsCategory: String = ""
}



class NewsRealm: Object {
    dynamic var newsID: String = ""
    dynamic var newsTitle: String = ""
    dynamic var newsFullText: String = ""
    dynamic var newsAutor: String = ""
    dynamic var newsCommentCount: String = ""
    dynamic var newsSeenCount: String = ""
    dynamic var newsDate: String = ""
    dynamic var newsCategory: String = ""
}

then after parse json you call insertOrUpdate and map data with NewsRealm :

func insertOrUpdate(news: News) {
    let realm = try! Realm()
    try! realm.write({
        let newsRealm = NewsRealm()
        newsRealm.newsTitle = news.newsTitle
        newsRealm.newsAutor = news.newsAutor
        newsRealm.newsFullText = news.newsFullText
        .
        .
        .
        realm.add(newsRealm)
        })
}