Skip to content

Commit

Permalink
Add option to sort
Browse files Browse the repository at this point in the history
  • Loading branch information
evermeer committed Jan 20, 2016
1 parent b3613ff commit 14c9da0
Show file tree
Hide file tree
Showing 7 changed files with 116 additions and 10 deletions.
2 changes: 1 addition & 1 deletion AppMessage/AppMessage/AppDelegate.swift
Expand Up @@ -19,7 +19,7 @@ class AppDelegate: UIResponder, UIApplicationDelegate {
// Only call this line once. It will make sure the recordType are there in iCloud.
// After this, go to the iCloud dashboard and make all metadata for each recordType queryable and sortable!
// If you use this in your own project, then make sure that the fields are not nil otherwise the field will not be created.
EVCloudKitDao.publicDB.createRecordTypes([Message(), Asset(), News(), Invoice()])
// EVCloudKitDao.publicDB.createRecordTypes([Message(), Asset(), News(), Invoice()])


// During development you will probably play around with subscriptins.
Expand Down
9 changes: 8 additions & 1 deletion AppMessage/AppMessage/CloudKit/EVCloudData.swift
Expand Up @@ -164,6 +164,10 @@ public class EVCloudData: NSObject {
A dictionary of predicates. Each filterId is a dictionary entry containing a predicate
*/
public var predicates = Dictionary<String, NSPredicate>()
/**
A dictionary of sort orders. Each filterId is a dictionary entry containging the sortOrder for that filter.
*/
public var sortOrders = Dictionary<String, OrderBy>()
/**
A dictionary of insert event handlers. Each filterId is a dictionary entry containing a insert event handler
*/
Expand Down Expand Up @@ -525,6 +529,7 @@ public class EVCloudData: NSObject {
}
dataIsUpdated(filter)
}
data[filter] = (data[filter]! as NSArray).sortedArrayUsingDescriptors(sortOrders[filter]!.sortDescriptors()) as? [EVCloudKitDataObject]
} else { // An update of a field that is used in the predicate could trigger a delete from that set.
EVLog("Object not for filter \(filter)")
if itemID != nil {
Expand Down Expand Up @@ -664,6 +669,7 @@ public class EVCloudData: NSObject {
public func connect<T:EVCloudKitDataObject>(
type: T,
predicate: NSPredicate,
orderBy: OrderBy = Descending(field: "creationDate"),
filterId: String,
cachingStrategy: CachingStrategy = CachingStrategy.Direct,
postNotifications: Bool? = nil,
Expand Down Expand Up @@ -704,6 +710,7 @@ public class EVCloudData: NSObject {
}
self.recordType[filterId] = EVReflection.swiftStringFromClass(type)
self.predicates[filterId] = predicate
self.sortOrders[filterId] = orderBy
self.cachingLastWrite[filterId] = NSDate()
self.cachingChangesCount[filterId] = 0
self.cachingStrategies[filterId] = cachingStrategy
Expand Down Expand Up @@ -749,7 +756,7 @@ public class EVCloudData: NSObject {

dao.subscribe(type, predicate:predicate, filterId: filterId, configureNotificationInfo:configureNotificationInfo ,errorHandler: errorHandler)

dao.query(type, predicate: predicate, completionHandler: { results, isFinished in
dao.query(type, predicate: predicate, orderBy: orderBy, completionHandler: { results, isFinished in
if self.data[filterId] != nil && self.data[filterId]! == results && self.data[filterId]!.count > 0 {
return false // Result was already returned from cache
}
Expand Down
105 changes: 101 additions & 4 deletions AppMessage/AppMessage/CloudKit/EVCloudKitDao.swift
Expand Up @@ -582,9 +582,10 @@ public class EVCloudKitDao {
- parameter errorHandler: The function that will be called when there was an error
:return: No return value
*/
public func query<T:EVCloudKitDataObject>(type:T, completionHandler: (results: [T], isFinished: Bool) -> Bool, errorHandler:((error: NSError) -> Void)? = nil) {
public func query<T:EVCloudKitDataObject>(type:T, orderBy: OrderBy = Descending(field: "creationDate"), completionHandler: (results: [T], isFinished: Bool) -> Bool, errorHandler:((error: NSError) -> Void)? = nil) {
let recordType = EVReflection.swiftStringFromClass(type)
let query = CKQuery(recordType: recordType, predicate: NSPredicate(value: true))
query.sortDescriptors = orderBy.sortDescriptors()
queryRecords(type, query:query, completionHandler: completionHandler, errorHandler: errorHandler)
}

Expand All @@ -598,11 +599,12 @@ public class EVCloudKitDao {
- parameter errorHandler: The function that will be called when there was an error
:return: No return value
*/
public func query<T:EVCloudKitDataObject>(type:T, referenceRecordName: String, referenceField: String ,completionHandler: (results: [T], isFinished: Bool) -> Bool, errorHandler:((error: NSError) -> Void)? = nil) {
public func query<T:EVCloudKitDataObject>(type:T, referenceRecordName: String, referenceField: String, orderBy: OrderBy = Descending(field: "creationDate"), completionHandler: (results: [T], isFinished: Bool) -> Bool, errorHandler:((error: NSError) -> Void)? = nil) {
let recordType = EVReflection.swiftStringFromClass(type)
let parentId = CKRecordID(recordName: referenceRecordName)
let parent = CKReference(recordID: parentId, action: CKReferenceAction.None)
let query = CKQuery(recordType: recordType, predicate: NSPredicate(format: "%K == %@", referenceField ,parent))
query.sortDescriptors = orderBy.sortDescriptors()
queryRecords(type, query:query, completionHandler: completionHandler, errorHandler: errorHandler)
}

Expand All @@ -615,9 +617,10 @@ public class EVCloudKitDao {
- parameter errorHandler: The function that will be called when there was an error
:return: No return value
*/
public func query<T:EVCloudKitDataObject>(type:T, predicate: NSPredicate, completionHandler: (results: [T], isFinished: Bool) -> Bool, errorHandler:((error: NSError) -> Void)? = nil){
public func query<T:EVCloudKitDataObject>(type:T, predicate: NSPredicate, orderBy: OrderBy = Descending(field: "creationDate"), completionHandler: (results: [T], isFinished: Bool) -> Bool, errorHandler:((error: NSError) -> Void)? = nil){
let recordType = EVReflection.swiftStringFromClass(type)
let query: CKQuery = CKQuery(recordType: recordType, predicate: predicate)
query.sortDescriptors = orderBy.sortDescriptors()
queryRecords(type, query:query, completionHandler: completionHandler, errorHandler: errorHandler)
}

Expand All @@ -630,9 +633,10 @@ public class EVCloudKitDao {
- parameter errorHandler: The function that will be called when there was an error
:return: No return value
*/
public func query<T:EVCloudKitDataObject>(type:T, tokens: String ,completionHandler: (results: [T], isFinished: Bool) -> Bool, errorHandler:((error: NSError) -> Void)? = nil) {
public func query<T:EVCloudKitDataObject>(type:T, tokens: String, orderBy: OrderBy = Descending(field: "creationDate"), completionHandler: (results: [T], isFinished: Bool) -> Bool, errorHandler:((error: NSError) -> Void)? = nil) {
let recordType = EVReflection.swiftStringFromClass(type)
let query = CKQuery(recordType: recordType, predicate: NSPredicate(format: "allTokens TOKENMATCHES[cdl] %@", tokens))
query.sortDescriptors = orderBy.sortDescriptors()
queryRecords(type, query:query, completionHandler: completionHandler, errorHandler: errorHandler)
}

Expand Down Expand Up @@ -1093,3 +1097,96 @@ public class EVCloudKitDao {
return dictionary
}
}



/**
Enum that will be used to specify the order
- Ascending: Sort in ascending order
- Descending: Sort in descending order
*/
public enum SortDirection {
case Ascending,
Descending
}

/// Base class for the sort object
public class OrderBy {
var field: String = ""
var direction: SortDirection = .Descending
var parent: OrderBy?

/**
Convenience init for creating an order object with all the parameters
- parameter field: Sort on what field
- parameter parent: When we sort on multiple fields then we need a chaing of OrderBy objects
- parameter direction: Do we sort ascending or descending
*/
public convenience init(field: String, parent: OrderBy? = nil, direction: SortDirection) {
self.init()
self.field = field
self.direction = direction
self.parent = parent
}

/**
Chain a second sort in ascending order
- parameter field: The field that we want to sort on
- returns: An OrderBy object
*/
public func Ascending(field: String) -> OrderBy {
return OrderBy(field: field, parent: self, direction: .Ascending)
}

/**
Chain a second sort in descending order
- parameter field: The field that we want to sort on
- returns: An OrderBy object
*/
public func Descending(field: String) -> OrderBy {
return OrderBy(field: field, parent: self, direction: .Descending)
}

/**
Build up an array of sortDescriptors
- returns: The array of sortDescriptors
*/
public func sortDescriptors() -> [NSSortDescriptor] {
var result: [NSSortDescriptor] = parent?.sortDescriptors() ?? []
result.append( NSSortDescriptor(key: field, ascending: (direction == .Ascending)))
return result
}
}

/// The initial OrderBy class for an ascending order
public class Ascending: OrderBy {
/**
Initialise an ascending OrderBy object
- parameter field: The field where to sort on
*/
public convenience required init(field: String) {
self.init(field: field, parent: nil, direction: .Ascending)
}
}

// The initial OrderBy class for a descending order
public class Descending: OrderBy {
/**
Initialise an descending OrderBy object
- parameter field: The field where to sort on
*/
public convenience required init(field: String) {
self.init(field: field, parent: nil, direction: .Descending)
}
}


1 change: 1 addition & 0 deletions AppMessage/AppMessage/CloudKit/EVCloudKitEnums.swift
Expand Up @@ -156,3 +156,4 @@ func !=(leftPart: CachingStrategy, rightPart: CachingStrategy) -> Bool {
return !(leftPart == rightPart)
}


Expand Up @@ -148,6 +148,7 @@ class LeftMenuViewController: UIViewController, UITableViewDataSource, UITableVi
EVCloudData.publicDB.connect(
News()
, predicate: NSPredicate(value: true)
, orderBy: Ascending(field: "Subject").Descending("creationDate")
, filterId: "News_All"
, configureNotificationInfo: { notificationInfo in
//notificationInfo.alertBody = "News update"
Expand Down
4 changes: 2 additions & 2 deletions AppMessage/AppMessage/Controlers/NewsViewController.swift
Expand Up @@ -68,8 +68,8 @@ class NewsViewController: UIViewController, UITableViewDataSource, UITableViewDe

//This line all you need to get the correct data for the cell
if let news: News = EVCloudData.publicDB.data["News_All"]![indexPath.row] as? News {
cell.textLabel?.text = news.Subject
cell.detailTextLabel?.text = news.Body
cell.textLabel?.text = "\(news.Subject)"
cell.detailTextLabel?.text = "(\(news.creationDate)) - \(news.Body)"
}

return cell;
Expand Down
4 changes: 2 additions & 2 deletions AppMessage/AppMessage/DataObjects/Message.swift
Expand Up @@ -20,7 +20,7 @@ class Message: EVCloudKitDataObject {
var From_ID: String = ""
func setFromFields(id: String) {
self.From_ID = id
self.From = CKReference(recordID: CKRecordID(recordName: id), action: CKReferenceAction.None)
self.From = CKReference(recordID: CKRecordID(recordName: id), action: CKReferenceAction.DeleteSelf)
}
var FromFirstName: String = ""
var FromLastName: String = ""
Expand All @@ -30,7 +30,7 @@ class Message: EVCloudKitDataObject {
var To_ID: String = ""
func setToFields(id: String) {
self.To_ID = id
self.To = CKReference(recordID: CKRecordID(recordName: id), action: CKReferenceAction.None)
self.To = CKReference(recordID: CKRecordID(recordName: id), action: CKReferenceAction.DeleteSelf)
}
var ToFirstName: String = ""
var ToLastName: String = ""
Expand Down

0 comments on commit 14c9da0

Please sign in to comment.