Issue with creating and then updating existing elements in Realm database - swift

I have a realm database which consists of Year -> Month -> Day -> Items
arrows go from parent category to the child category.
I am able to save the calculation once but if I do it again it will throw an error that Month of a primary key 0 already exists. I do know what it exists that is why I want Realm to update it. As I want to save each month only once and each year only once.
//MARK: - Realm Database Saving option
#objc func saveCalculation(){
let date = Date()
let dateElements = getDate()
let yearObject = Year()
yearObject.number = dateElements.year
let monthObject = Month()
monthObject.number = dateElements.month
monthObject.monthName = dateElements.monthName
let dayObject = Day()
dayObject.id = realm.objects(Day.self).count
dayObject.date = date
dayObject.number = dateElements.day
dayObject.dayName = dateElements.dayNameInWeek
dayObject.hoursPerDay = hoursPerDay
dayObject.ratePerHour = ratePerHour
dayObject.minutesOfNormalPay = minutesOfNormalPay
dayObject.earnedPerDay = earnedPerDay
dayObject.howManyRows = rowViews.count
do {
try realm.write {
realm.add(yearObject, update: true)
yearObject.months.append(monthObject)
realm.add(monthObject, update: true)
monthObject.days.append(dayObject)
realm.add(dayObject, update: false)
for (index, row) in rowViews.enumerated() {
let item = Item()
item.id = index
item.date = date
item.amount = Double(row.amountTextField.text!) ?? 0.0
item.price = Double(row.priceTextField.text!) ?? 0.0
print("Item amount: \(item.amount) and price: \(item.price)")
dayObject.items.append(item)
realm.add(item)
}
}
} catch {
print(error.localizedDescription)
}
}
func getDate() -> (day: Int, dayNameInWeek: String, month: Int, monthName: String, year: Int) {
let date = Date()
let dayNameInWeek = date.getDayName()
let monthName = date.getMonthName()
let calendar = Calendar.current
let components = calendar.dateComponents([.year, .month, .day], from: date)
let year = components.year!
let month = components.month!
let day = components.day!
print(year)
print(month)
print(monthName)
print(day)
print(dayNameInWeek)
return (day,dayNameInWeek, month, monthName, year)
}
each database class respectively:
import Foundation
import RealmSwift
class Year: Object {
//#objc dynamic var year = Date()
#objc dynamic var id: Int = 0
#objc dynamic var number: Int = 2008
let months = List<Month>() //forward relationship to Months
override class func primaryKey() -> String {
return "id"
}
}
Month:
import Foundation
import RealmSwift
class Month: Object {
#objc dynamic var id: Int = 0
#objc dynamic var number: Int = 0
#objc dynamic var monthName: String = ""
#objc dynamic var monthYear: Int = 0
let days = List<Day>() //forward relationship to Days
let parentYear = LinkingObjects(fromType: Year.self, property: "months") //back relationship to year
override class func primaryKey() -> String {
return "id"
}
}
Day:
import Foundation
import RealmSwift
class Day: Object {
#objc dynamic var id: Int = 0
#objc dynamic var date: Date = Date()
#objc dynamic var number: Int = 0
#objc dynamic var dayName: String = ""
#objc dynamic var hoursPerDay: Double = 0.0
#objc dynamic var ratePerHour: Double = 0.0
#objc dynamic var minutesOfNormalPay: Double = 0.0
#objc dynamic var earnedPerDay: Double = 0.0
#objc dynamic var howManyRows: Int = 0
let items = List<Item>() //forward relationship to Items
let parentMonth = LinkingObjects(fromType: Month.self, property: "days") //back relationship to months
override class func primaryKey() -> String {
return "id"
}
}
Item:
import Foundation
import RealmSwift
class Item: Object {
#objc dynamic var id: Int = 0
#objc dynamic var date: Date = Date()
#objc dynamic var amount: Double = 0.0
#objc dynamic var price: Double = 0.0
let parentDay = LinkingObjects(fromType: Day.self, property: "items") //back relationship to days
}

I have managed to solve the problem with some if else conditions. If someone knows a cleeaner way of writing it then please post it below, as I am really interested of getting this code shortened.
//MARK: - Realm Database Saving option
#objc func saveCalculation(){
let date = Date()
let dateElements = getDate()
var isParentYear = false
var isParentMonth = false
let yearObject: Year
if let currentYearObject = realm.objects(Year.self).first(where: {$0.number == dateElements.year}) {
yearObject = currentYearObject
isParentYear = true
} else {
yearObject = Year()
yearObject.id = realm.objects(Year.self).count
yearObject.number = dateElements.year
}
let monthObject: Month
if let currentMonthObject = realm.objects(Month.self).first(where: {$0.monthYear == dateElements.year && $0.number == dateElements.month}) {
monthObject = currentMonthObject
isParentMonth = true
} else {
monthObject = Month()
monthObject.id = realm.objects(Month.self).count
monthObject.number = dateElements.month
monthObject.monthYear = dateElements.year
monthObject.monthName = dateElements.monthName
}
let dayObject = Day()
dayObject.id = realm.objects(Day.self).count
dayObject.date = date
dayObject.number = dateElements.day
dayObject.dayName = dateElements.dayNameInWeek
dayObject.hoursPerDay = hoursPerDay
dayObject.ratePerHour = ratePerHour
dayObject.minutesOfNormalPay = minutesOfNormalPay
dayObject.earnedPerDay = earnedPerDay
dayObject.howManyRows = rowViews.count
do {
try realm.write {
if isParentYear && isParentMonth{
print("Parent Year is: \(isParentYear) and parent Month is: \(isParentMonth)")
monthObject.days.append(dayObject)
realm.add(dayObject, update: false)
} else if isParentYear && !isParentMonth {
print("Parent Year is: \(isParentYear) and parent Month is: \(isParentMonth)")
yearObject.months.append(monthObject)
realm.add(monthObject, update: true)
monthObject.days.append(dayObject)
realm.add(dayObject, update: false)
} else if !isParentYear && !isParentMonth {
print("Parent Year is: \(isParentYear) and parent Month is: \(isParentMonth)")
realm.add(yearObject, update: true)
yearObject.months.append(monthObject)
realm.add(monthObject, update: true)
monthObject.days.append(dayObject)
realm.add(dayObject, update: false)
} else {
print("THISH SHOULD NEVER BE CALLED IF CALLED SOMETHING IS VERY WRONG")
}
for (index, row) in rowViews.enumerated() {
let item = Item()
item.id = index
item.date = date
item.amount = Double(row.amountTextField.text!) ?? 0.0
item.price = Double(row.priceTextField.text!) ?? 0.0
print("Item amount: \(item.amount) and price: \(item.price)")
dayObject.items.append(item)
realm.add(item)
}
}
} catch {
print(error.localizedDescription)
}
}

Related

Append SQLite query result to an existing model

This is how I read the data:
func read() -> [ChatModel] {
let queryStatementString = "SELECT * FROM chatoverview;"
var queryStatement: OpaquePointer? = nil
var psns = [ChatModel]()
if sqlite3_prepare_v2(db, queryStatementString, -1, &queryStatement, nil) == SQLITE_OK {
while sqlite3_step(queryStatement) == SQLITE_ROW {
let chatId = sqlite3_column_text(queryStatement, 0)
let partnerId = sqlite3_column_text(queryStatement, 1)
let partnerName = sqlite3_column_text(queryStatement, 2)
let createdDate = sqlite3_column_text(queryStatement, 3)
let lastMessage = sqlite3_column_text(queryStatement, 4)
let lastMessageDate = sqlite3_column_text(queryStatement, 5)
let partnerProfileImage = sqlite3_column_text(queryStatement, 6)
print("read")
print(chatId)
psns.append(ChatModel(dictionary: ["chatId": chatId!, "partnerId": partnerId!, "partnerName": partnerName!, "createdDate": createdDate!, "lastMessage": lastMessage!, "lastMessageDate": lastMessageDate!, "partnerProfileImage": partnerProfileImage!]))
}
}
The result from print(chatId) = "Optional(0x000000010d21fd50)" and I am not sure why the result is not a string.. anyway, in my ViewController I am trying to append this data to my existing ChatModel:
import Foundation
import FirebaseFirestore
class ChatModel {
var partnerId: String?
var partnerName: String?
var createdDate: Timestamp?
var lastMessage: String?
var lastMessageDate: Timestamp?
var chatId: String?
var partnerProfileimage: String?
init(dictionary: [String: Any]) {
partnerId = dictionary["partnerId"] as? String
partnerName = dictionary["partnerName"] as? String
createdDate = dictionary["createdDate"] as? Timestamp
chatId = dictionary["chatId"] as? String
lastMessage = dictionary["lastMessage"] as? String
lastMessageDate = dictionary["lastMessageDate"] as? Timestamp
partnerProfileimage = dictionary["partnerProfileimage"] as? String
}
}
Relevant code in my ViewController:
var test = [ChatModel]()
override func viewWillAppear(_ animated: Bool) {
super.viewWillAppear(animated)
test = db.read()
print(test.count) <---- 5 Items, correct number, my SQLite file also has the correct data / schema
for x in test {
print(x.lastMessage)
}
And here is the problem. x.lastMessage is always nil.
How can I append the SQL result to my existing model?

Swift – macOS `batteryLevel` property

In iOS there's a simple approach to get a level of iPhone battery:
UIDevice.current.batteryLevel
What's a macOS batteryLevel equivalent for MacBooks?
Getting the battery level in macOS is not as easy as in iOS, but it is still pretty easy. You have to use the IOKit framework for this.
You can use this code to read almost all of the important information from the internal battery.
InternalBattery.swift
import Foundation
import IOKit.ps
public class InternalBattery {
public var name: String?
public var timeToFull: Int?
public var timeToEmpty: Int?
public var manufacturer: String?
public var manufactureDate: Date?
public var currentCapacity: Int?
public var maxCapacity: Int?
public var designCapacity: Int?
public var cycleCount: Int?
public var designCycleCount: Int?
public var acPowered: Bool?
public var isCharging: Bool?
public var isCharged: Bool?
public var amperage: Int?
public var voltage: Double?
public var watts: Double?
public var temperature: Double?
public var charge: Double? {
get {
if let current = self.currentCapacity,
let max = self.maxCapacity {
return (Double(current) / Double(max)) * 100.0
}
return nil
}
}
public var health: Double? {
get {
if let design = self.designCapacity,
let current = self.maxCapacity {
return (Double(current) / Double(design)) * 100.0
}
return nil
}
}
public var timeLeft: String {
get {
if let isCharging = self.isCharging {
if let minutes = isCharging ? self.timeToFull : self.timeToEmpty {
if minutes <= 0 {
return "-"
}
return String(format: "%.2d:%.2d", minutes / 60, minutes % 60)
}
}
return "-"
}
}
public var timeRemaining: Int? {
get {
if let isCharging = self.isCharging {
return isCharging ? self.timeToFull : self.timeToEmpty
}
return nil
}
}
}
InternalFinder.swift:
import Foundation
import IOKit.ps
public class InternalFinder {
private var serviceInternal: io_connect_t = 0 // io_object_t
private var internalChecked: Bool = false
private var hasInternalBattery: Bool = false
public init() { }
public var batteryPresent: Bool {
get {
if !self.internalChecked {
let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue()
let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as Array
self.hasInternalBattery = sources.count > 0
self.internalChecked = true
}
return self.hasInternalBattery
}
}
fileprivate func open() {
self.serviceInternal = IOServiceGetMatchingService(kIOMasterPortDefault, IOServiceMatching("AppleSmartBattery"))
}
fileprivate func close() {
IOServiceClose(self.serviceInternal)
IOObjectRelease(self.serviceInternal)
self.serviceInternal = 0
}
public func getInternalBattery() -> InternalBattery? {
self.open()
if self.serviceInternal == 0 {
return nil
}
let battery = self.getBatteryData()
self.close()
return battery
}
fileprivate func getBatteryData() -> InternalBattery {
let battery = InternalBattery()
let snapshot = IOPSCopyPowerSourcesInfo().takeRetainedValue()
let sources = IOPSCopyPowerSourcesList(snapshot).takeRetainedValue() as Array
for ps in sources {
// Fetch the information for a given power source out of our snapshot
let info = IOPSGetPowerSourceDescription(snapshot, ps).takeUnretainedValue() as! Dictionary<String, Any>
// Pull out the name and capacity
battery.name = info[kIOPSNameKey] as? String
battery.timeToEmpty = info[kIOPSTimeToEmptyKey] as? Int
battery.timeToFull = info[kIOPSTimeToFullChargeKey] as? Int
}
// Capacities
battery.currentCapacity = self.getIntValue("CurrentCapacity" as CFString)
battery.maxCapacity = self.getIntValue("MaxCapacity" as CFString)
battery.designCapacity = self.getIntValue("DesignCapacity" as CFString)
// Battery Cycles
battery.cycleCount = self.getIntValue("CycleCount" as CFString)
battery.designCycleCount = self.getIntValue("DesignCycleCount9C" as CFString)
// Plug
battery.acPowered = self.getBoolValue("ExternalConnected" as CFString)
battery.isCharging = self.getBoolValue("IsCharging" as CFString)
battery.isCharged = self.getBoolValue("FullyCharged" as CFString)
// Power
battery.amperage = self.getIntValue("Amperage" as CFString)
battery.voltage = self.getVoltage()
// Various
battery.temperature = self.getTemperature()
// Manufaction
battery.manufacturer = self.getStringValue("Manufacturer" as CFString)
battery.manufactureDate = self.getManufactureDate()
if let amperage = battery.amperage,
let volts = battery.voltage, let isCharging = battery.isCharging {
let factor: CGFloat = isCharging ? 1 : -1
let watts: CGFloat = (CGFloat(amperage) * CGFloat(volts)) / 1000.0 * factor
battery.watts = Double(watts)
}
return battery
}
fileprivate func getIntValue(_ identifier: CFString) -> Int? {
if let value = IORegistryEntryCreateCFProperty(self.serviceInternal, identifier, kCFAllocatorDefault, 0) {
return value.takeRetainedValue() as? Int
}
return nil
}
fileprivate func getStringValue(_ identifier: CFString) -> String? {
if let value = IORegistryEntryCreateCFProperty(self.serviceInternal, identifier, kCFAllocatorDefault, 0) {
return value.takeRetainedValue() as? String
}
return nil
}
fileprivate func getBoolValue(_ forIdentifier: CFString) -> Bool? {
if let value = IORegistryEntryCreateCFProperty(self.serviceInternal, forIdentifier, kCFAllocatorDefault, 0) {
return value.takeRetainedValue() as? Bool
}
return nil
}
fileprivate func getTemperature() -> Double? {
if let value = IORegistryEntryCreateCFProperty(self.serviceInternal, "Temperature" as CFString, kCFAllocatorDefault, 0) {
return value.takeRetainedValue() as! Double / 100.0
}
return nil
}
fileprivate func getDoubleValue(_ identifier: CFString) -> Double? {
if let value = IORegistryEntryCreateCFProperty(self.serviceInternal, identifier, kCFAllocatorDefault, 0) {
return value.takeRetainedValue() as? Double
}
return nil
}
fileprivate func getVoltage() -> Double? {
if let value = getDoubleValue("Voltage" as CFString) {
return value / 1000.0
}
return nil
}
fileprivate func getManufactureDate() -> Date? {
if let value = IORegistryEntryCreateCFProperty(self.serviceInternal, "ManufactureDate" as CFString, kCFAllocatorDefault, 0) {
let date = value.takeRetainedValue() as! Int
let day = date & 31
let month = (date >> 5) & 15
let year = ((date >> 9) & 127) + 1980
var components = DateComponents()
components.calendar = Calendar.current
components.day = day
components.month = month
components.year = year
return components.date
}
return nil
}
}
Usage:
let internalFinder = InternalFinder()
if let internalBattery = internalFinder.getInternalBattery() {
// Internal battery found, access properties here.
}

Swift: Bug when try to access value of object in array

I encounter a very strange bug, I have a PodEvent type array, and with a second function I get another array that I cast, when I make a print of the casted array with the result it shows me all the objects of the board...
PodEvent {
eventID = 2;
podID = 1;
drinkDate = 2018-09-25 10:00:00 +0000;
actualDrinkingTime = (null);
keyDate = 2018-09-25 13:00;
rawState = Forgotten;
}
But when I want to access the value of the object it returns to me as the default values! for example:
print(self.podEvents[1].eventID)
print(self.podEvents[1].podID)
outpout:
-1
-1
Here my class:
class PodEvent: Object {
#objc var eventID: Int = -1
#objc var podID: Int = -1
#objc var drinkDate: Date = Date()
#objc var actualDrinkingTime: Date? = Date()
var state: PodState = .future
#objc var keyDate: String = ""
#objc private var rawState: String!
convenience init(eventID: Int, podID: Int, drinkDate: Date, actualDrinkingTime: Date?, state: PodState){
self.init()
self.eventID = eventID
self.podID = podID
self.drinkDate = drinkDate
self.actualDrinkingTime = actualDrinkingTime
self.state = state
self.rawState = state.state
}
func setState(state: PodState){
self.state = state
rawState = state.state
}
override class func primaryKey() -> String? {
return "keyDate"
}
This bug is very strange
My code to fetch my array:
//Fetch pod history in internal database
self.databaseManager.fetch(object: PodEvent.self, predicate: nil, sortedBy: "keyDate", ascending: true) { success, results, error in
guard error == nil else {
Alerts.alertMessage(for: self, title: "ERROR".localized,
message: error!.localizedDescription,
closeHandler: nil)
return
}
self.podEvents = (results as! [PodEvent])
self.pods = pods
print(self.podEvents[1].eventID)
print(self.podEvents[1].podID)
}
and:
func fetch(object: Object.Type, predicate: NSPredicate?, sortedBy: String, ascending: Bool, completion: DatabaseCompletion?) {
do {
let realm = try Realm()
let objects: Results<Object>!
if let predicate = predicate {
objects = realm.objects(object).filter(predicate).sorted(byKeyPath: sortedBy, ascending: ascending)
} else {
objects = realm.objects(object).sorted(byKeyPath: sortedBy, ascending: ascending)
}
let objectsArray = Array(objects)
completion?(true, objectsArray, nil)
} catch let error {
print("Could not write object (type \(object)) to Realm:", error.localizedDescription)
completion?(false, nil, error)
}
}
im using realm
Your object definition is flawed, you need to add the dynamic keyword to all persisted properties.
class PodEvent: Object {
#objc dynamic var eventID = -1
#objc dynamic var podID = -1
#objc dynamic var drinkDate = Date()
#objc dynamic var actualDrinkingTime: Date? = Date()
var state: PodState = .future
#objc dynamic var keyDate = ""
#objc dynamic private var rawState: String!
...
}

iOS - UI Label Not Updating

I am trying to build a weather app with AlamoFire and i am getting the JSON Response as expected but when i am trying to update the date to UI Label, my variable is returning a nil. if anyone get a chance to let me know where i am going wrong
import UIKit
class WeatherVC: UIViewController {
#IBOutlet weak var dateLbl: UILabel!
#IBOutlet weak var weatherType: UILabel!
#IBOutlet weak var cityname: UILabel!
#IBOutlet weak var currentTemp: UILabel!
var weatherConstants = WeatherConstant()
override func viewDidLoad() {
super.viewDidLoad()
// updateUI()
//
weatherConstants.downloadCurrentWeather {
self.updateUI()
}
weatherConstants = WeatherConstant()
print(Current_Weather_Url)
}
func updateUI() {
weatherType.text = weatherConstants.weatherType
cityname.text = weatherConstants.cityName
print("current city name is \(weatherConstants.weatherType)")
}
}
Weather Constants
import UIKit
import Alamofire
class WeatherConstant {
var _cityName :String!
var _currentTemp : Double!
var _weatherType : String!
var _highTemp : String!
var _date :String!
var cityName :String {
if _cityName == nil {
_cityName = ""
}
return _cityName
}
var currentTemp : Double{
if _currentTemp == nil {
_currentTemp = 0.0
}
return _currentTemp
}
var weatherType : String {
if _weatherType == nil {
_weatherType = ""
}
return _weatherType
}
var highTemp : String {
if _highTemp == nil {
_highTemp = ""
}
return _highTemp
}
var date : String {
if _date == nil {
_date = ""
}
let dateFormatter = DateFormatter()
dateFormatter.dateStyle = .long
dateFormatter.timeStyle = .none
let currentDate = dateFormatter.string(from: Date())
self._date = "Today, \(currentDate)"
return _date
}
//func downloadWeatherDetails(completed : DownloadComplete) ===> downloadWeatherDetails(completed : #escaping DownloadComplete)
func downloadCurrentWeather(completed: #escaping DownloadComplete) {
Alamofire.request(Current_Weather_Url).responseJSON{ response in
let result = response.result
// print(result)
debugPrint(result)
if let dict = result.value as? Dictionary<String, AnyObject>{
if let name = dict["name"] as? String {
self._cityName = name
print("current name is \(self._cityName)")
}
if let currentTemp = dict["weather"] as? [Dictionary<String, AnyObject>] {
if let main = currentTemp[0]["main"] as? String{
self._weatherType = main
print("Current Weather Type \(self._weatherType)")
}
}
}
completed()
}
}
}
JSON Response
https://samples.openweathermap.org/data/2.5/weather?lat=35&lon=139&appid=e9a34088739f38c517b4a45084f5ed82
SUCCESS: {
base = stations;
clouds = {
all = 0;
};
cod = 200;
coord = {
lat = "35.02";
lon = "139.01";
};
dt = 1485792967;
id = 1907296;
main = {
"grnd_level" = "1013.75";
humidity = 100;
pressure = "1013.75";
"sea_level" = "1023.22";
temp = "285.514";
"temp_max" = "285.514";
"temp_min" = "285.514";
};
name = Tawarano;
sys = {
country = JP;
message = "0.0025";
sunrise = 1485726240;
sunset = 1485763863;
};
weather = (
{
description = "clear sky";
icon = 01n;
id = 800;
main = Clear;
}
);
wind = {
deg = 311;
speed = "5.52";
};
}
Current Weather Type Optional("Clear")----> this the weather type i am trying to provide to UIlabel
current city name is Optional("") ------> Here i am trying to print what data is in UILabel but its returning empty string
2018-08-07 11:18:09.567868-0700 WeatherApp1.1[82321:3248301] [BoringSSL] Function boringssl_session_errorlog: line 2881 [boringssl_session_read] SSL_ERROR_ZERO_RETURN(6): operation failed because the connection was cleanly shut down with a close_notify alert
You're overwriting the weatherConstants value with a new object in viewDidLoad. Try removing that.
(Longer explanation: you're correctly creating a weatherConstants object, and asking it to fetch data. But while that's happening, you create a second instance of that object which overwrites the first. So while the first instance completes the network request and tells your UI to redraw, the UI is getting its data from the second instance of WeatherConstants)

Filter by day from NSDate in Realm, Swift

So, I put NSDate in Realm model:
class GeneralList: Object {
dynamic var createdAt = NSDate()
dynamic var notes = ""
}
How to get, for example, all 'notes' in 27.03.2016 ?
You can implement this function, from Rafael's answer
private func createMessageRealmModelFromIncomingMessage(incomingMessage: MessageRestModel) -> MessageRealmModel {
let messageRealmModel = MessageRealmModel()
messageRealmModel.id = incomingMessage.id!
messageRealmModel.messageType = "CHAT_MESSAGE"
messageRealmModel.value = (incomingMessage.content?.value)!
messageRealmModel.senderId = incomingMessage.senderId!
messageRealmModel.recipientId = incomingMessage.recipientId!
messageRealmModel.sendDate = incomingMessage.sendDate!
messageRealmModel.serverDeliveryDate = incomingMessage.serverDeliveryDate!
messageRealmModel.receiverDeliveryDate = NSDate().msFromEpoch()
return messageRealmModel
}
And then use it as a parameter for Realm's filter function like this:
var c = NSDateComponents()
c.year = 2016
c.month = 3
c.day = 27
var date = NSCalendar(identifier: NSCalendarIdentifierGregorian)?.dateFromComponents(c)
let generalListsInDay = realm.objects(GeneralList).filter(self.predicateForDayFromDate(day))
After executing this code your generalListsInDay should contain all GeneralList's in 27.03.2016
So, I find easy way:
Create public extension for String and create function with separate NSDate:
public static func sepaDate(whatNeed: String) -> String {
var currentDate = NSDate()
let calendar = NSCalendar(calendarIdentifier: NSCalendarIdentifierGregorian)
let dateComponents = calendar!.components([.Day, .Month, .Year, .Minute, .Hour], fromDate: currentDate)
var forReturn: String = "0"
switch whatNeed {
case "day":
let valu = String(dateComponents.day)
forReturn = valu
case "month":
let valu = String(dateComponents.month)
forReturn = valu
case "year":
let valu = String(dateComponents.year)
forReturn = valu
case "hour":
let valu = String(dateComponents.hour)
forReturn = valu
case "minute":
let valu = String(dateComponents.minute)
forReturn = valu
default: print("Error")
}
return forReturn
}
}
In Realm class, create separate date:
dynamic var minute = String.sepaDate("minute")
dynamic var hour = String.sepaDate("hour")
dynamic var day = String.sepaDate("day")
dynamic var month = String.sepaDate("month")
dynamic var year = String.sepaDate("year")
In ViewController call to predicate
let dayday = String(dateComponents.day)
let monthmonth = String(dateComponents.month)
let yearyear = String(dateComponents.year)
let predicate = NSPredicate(format: "day = %# AND month = %# AND year = %#", dayday, monthmonth, yearyear)
generalRecords = uiRealm.objects(GeneralList).filter(predicate)
I hope it's help somebody...