[Swift]从对 JSON 数据保存Realm

发布时间: 2017/3/5 23:30:24
注意事项: 本文中文内容可能为机器翻译,如要查看英文原文请点击上面连接.

我是新来 Realm 和我有一些问题,试图将 JSON 数据保存从 web 服务到我 Realm DB。

这是 JSON:

{  
   "Programacao":[  
      {  
         "Dia":"5",
         "Idp":"1833",
         "Programa":"T\u00e1 Na Hora",
         "Inicio":"06:00",
         "Final":"08:00",
         "Data":"08\/04\/2016"
      },
      {  
         "Dia":"5",
         "Idp":"1834",
         "Programa":"Bom dia Chiru",
         "Inicio":"08:00",
         "Final":"09:00",
         "Data":"08\/04\/2016"
      },
      {  
         "Dia":"5",
         "Idp":"1835",
         "Programa":"Conex\u00e3o",
         "Inicio":"09:00",
         "Final":"11:00",
         "Data":"08\/04\/2016"
      },
      {  
         "Dia":"5",
         "Idp":"1836",
         "Programa":"As Mais Pedidas",
         "Inicio":"11:00",
         "Final":"12:00",
         "Data":"08\/04\/2016"
      },
      {  
         "Dia":"5",
         "Idp":"1837",
         "Programa":"Casa da Sogra",
         "Inicio":"12:00",
         "Final":"13:00",
         "Data":"08\/04\/2016"
      },
      {  
         "Dia":"5",
         "Idp":"1838",
         "Programa":"Canal Livre",
         "Inicio":"13:00",
         "Final":"15:00",
         "Data":"08\/04\/2016"
      },
      {  
         "Dia":"5",
         "Idp":"18",
         "Programa":"Batid\u00e3o da Chiru",
         "Inicio":"15:00",
         "Final":"17:00",
         "Data":"08\/04\/2016"
      },
      {  
         "Dia":"5",
         "Idp":"1827",
         "Programa":"Sul Bandas",
         "Inicio":"17:00",
         "Final":"19:00",
         "Data":"08\/04\/2016"
      },
      {  
         "Dia":"5",
         "Idp":"1828",
         "Programa":"Voz do Brasil",
         "Inicio":"19:00",
         "Final":"20:00",
         "Data":"08\/04\/2016"
      },
      {  
         "Dia":"5",
         "Idp":"1831",
         "Programa":"Al\u00f4 Chiru",
         "Inicio":"20:00",
         "Final":"23:59",
         "Data":"08\/04\/2016"
      }
   ]
}

我创建了以下结构︰

Realm对象类︰

import Foundation
import RealmSwift

class ROListing: Object {     // Programação da Rádio

  dynamic var id              = 0

  dynamic var showName        = ""
  dynamic var showId          = ""

  dynamic var showStartTime   = ""
  dynamic var showEndTime     = ""

  dynamic var showNumericDate = ""
  dynamic var showDate        = ""

  override static func primaryKey() -> String? {
    return "id"
  }

}

对象操作类︰

import Alamofire
import SwiftyJSON
import Foundation

class Listing: ResponseJSONObjectSerializable {

  var showName        :String?    // nomePrograma
  var showId          :String?    // idp

  var showStartTime   :String?    // inicioPrograma
  var showEndTime     :String?    // finalPrograma

  var showNumericDate :String?    // dia
  var showDate        :String?    // data

  required init?(json: JSON) {

    self.showName         = json["Programa"].string
    self.showId           = json["Idp"].string

    self.showStartTime    = json["Inicio"].string
    self.showEndTime      = json["Final"].string

    self.showNumericDate  = json["Dia"].string
    self.showDate         = json["Data"].string

  }

  required init() { }
}

class ListingArray: ResponseJSONObjectSerializable {

  var showArray: [Listing]?       // Programacao

  required init?(json: JSON) {

    if let arrayJson = json["Programacao"].array {
      self.showArray = []

      for json in arrayJson {
        let instance = Listing(json: json)
        self.showArray?.append(instance!)
      }

    }

  }

  required init() { }
}

与通过 web 服务连接︰

func getRadioListing(success: () -> ()) {

    guard let url = apiController.createURLWithComponentsForListingsWith(appId: "63") else {
      print("Invlaid URL!")
      return
    }

    print(url)

    Alamofire.request(.GET, url).responseObject {
      (response: Response<ListingArray, NSError>) in

      if let jsonResults = response.result.value {
        self.listings = jsonResults

        for listing in self.listings.showArray! {
          RealmObjectManager.sharedInstance.createUpdateDB(withListing: listing)
        }

        success()

      } else {
        print("Error parsing JSON!")
        return
      }
    }

  }

最后,实际上保存到对象的方法 Realm DB。

  func createUpdateDB(withListing listing: Listing) {

    print(Realm.Configuration.defaultConfiguration.path!)

    if self.listingArray.count == 0 {

      do {

        try self.realm.write {

          let newListing = ROListing()

          newListing.showName = listing.showName!
          newListing.showId = listing.showId!

          newListing.showStartTime = listing.showStartTime!
          newListing.showEndTime = listing.showEndTime!

          newListing.showNumericDate = listing.showNumericDate!
          newListing.showDate = listing.showDate!

          self.realm.add(newListing)
        }

      } catch let error as NSError {
        print("Error creating Listing DB: \(error.userInfo)")
      }
    }
  }

但是我不能将所有的节目进入 DB。谁能帮我一下吗?

在此先感谢 !

解决方法 1:

我不能说肯定不会出现错误 log ,但它确实出现,你会有问题,因为你主要的关键。 Realm 强制唯一性主键,所以如果你尝试添加一个对象到 realm 与现有对象相同的主键相同 type 它将打破。就我所知,你将主键设置为 0,默认情况下,但你不更新它与一个唯一的值,然后再进行保存。

如果你只需要为每个对象的唯一标识符和顺序并不重要,这是一个好的解决方案︰

dynamic var id: String = NSUUID().UUIDString
赞助商