0

I am using GRDB to sync my JSON payload to SQLite however I am encountering an error whenever I have an array of other items within the main payload.

fatal error: unexpectedly found nil while unwrapping an Optional value

My JSON is:

{ "newsData": [
  {
    "newsID" : 6,
    "content" : "Test",
    "author" : "Test Author",
    "published" : 1,
    "title" : "Test news",
    "dateAdded" : "2015-12-18 11:33:15",
    "imagePath" : null,
    "newsCategoryData" : [

    ],
    "shortDescription" : "Test",
    "newsTagData" : [

    ],
    "lastModified" : null
  },

as you can see I have newsCategoryData and newsTagData as arrays. The sync is:

 do {
   let jsonString =
      "{ \"newsData\": " +
        "\(responseJSON["newsData"]) " +
      "}"
    try dbQueue.inTransaction { db in
      try self.synchronizeNewsWithJSON(jsonString, inDatabase: db)
      return .Commit
    }
}

The issue is newsCategoryData and newsTagData because if I remove those from the payload everything syncs correctly. Is it possible to ignore these 2 items when performing a sync as I will sync these 2 at a later stage.

Thanks

EDIT:

func synchronizeNewsWithJSON(jsonString: String, inDatabase db: Database) throws {
    let jsonData = jsonString.dataUsingEncoding(NSUTF8StringEncoding)!
    let json = try NSJSONSerialization.JSONObjectWithData(jsonData, options: []) as! NSDictionary

    func jsonNewsID(jsonNews: NSDictionary) -> Int64 {
        return (jsonNews["newsID"] as! NSNumber).longLongValue
    }

    let jsonNews = (json["newsData"] as! [NSDictionary]).sort {
        return jsonNewsID($0) < jsonNewsID($1)
    }

    let news = NewsModel.fetchAll(db, "SELECT * FROM news ORDER BY newsID")

    for mergeStep in sortedMerge(
        left: news,
        right: jsonNews,
        leftKey: { $0.newsID! },
        rightKey: jsonNewsID)
    {
        switch mergeStep {
        case .Left(let news):
            try news.delete(db)

        case .Right(let jsonNews):
            let row = Row(dictionary: jsonNews)!
            let news = NewsModel(row: row)
            try news.insert(db)

        case .Common(let news, let jsonNews):
            news.updateFromJSON(jsonNews)
            try news.update(db)
        }
    }
}
4

0 回答 0