Guest User

Untitled

a guest
Feb 12th, 2018
167
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.64 KB | None | 0 0
  1. class User: Object {
  2.  
  3. @objc dynamic var email: String = ""
  4. @objc dynamic var password: String = ""
  5. let subscriptions = List<Subscription>()
  6.  
  7. convenience init(email: String, password: String) {
  8. self.init()
  9.  
  10. self.email = email
  11. self.password = password
  12. }
  13. }
  14.  
  15. class Subscription: Object {
  16.  
  17. @objc dynamic var id: String?
  18. @objc dynamic var status: String?
  19. @objc dynamic var lastUpdated: Date?
  20.  
  21. convenience init(id: String, status: String) {
  22. self.init()
  23.  
  24. self.id = id
  25. self.status = status
  26. lastUpdated = Date()
  27. }
  28. }
  29.  
  30. class func create(user: User, _ completion: (Error?) -> Void) {
  31.  
  32. do {
  33. let ctx = try Realm()
  34.  
  35. if ctx.isEmpty {
  36. try ctx.write {
  37. ctx.add(user)
  38.  
  39. completion(nil)
  40. }
  41. } else {
  42. completion(nil)
  43. }
  44. } catch {
  45. completion(DBError.unableToAccessDatabase)
  46. }
  47. }
  48.  
  49. class func add(Subscription: Subscription, _ completion: (Error?) -> Void) {
  50.  
  51. do {
  52. let ctx = try Realm()
  53.  
  54. if let user = ctx.objects(User.self).last {
  55.  
  56. let predicate = NSPredicate(format: "id = %@", subscription.id!)
  57. let sub = user.subscriptions.filter(predicate).first
  58. if sub == nil {
  59. try ctx.write({
  60. user.subscriptions.append(subscription)
  61. completion(nil)
  62. })
  63. }
  64. }
  65. } catch {
  66. completion(DBError.unableToAccessDatabase)
  67. }
  68. }
Add Comment
Please, Sign In to add comment