Sort HKSampleQuery items by Quantity - ios

I want to fetch HealthKit quantity data and sort them by quantity value. Is it possible?
I know I can filter them by using HKPredicateKeyPathQuantityin the NSPredicate but I can't find similar key for sorting
Example
let type = HKObjectType.quantityTypeForIdentifier(HKQuantityTypeIdentifierHeight)
let sort = [
NSSortDescriptor(key: HKSampleSortIdentifierStartDate, ascending: true),
NSSortDescriptor(key: HKSampleSortIdentifierEndDate, ascending: true),
//I want one more Sort Item here :(
//NSSortDescriptor(key: SortIdentifierIdeQuantity, ascending: true)
]
let predicate = NSPredicate(format: "\(HKPredicateKeyPathStartDate) > %# AND \(HKPredicateKeyPathStartDate) < %# AND \(HKPredicateKeyPathQuantity) == %#",
argumentArray:[start, end, value])
let query = HKSampleQuery(sampleType: type, predicate: predicate, limit: limit, sortDescriptors: sort) { query, res, error in
completion(res, error)
}
healthKit.executeQuery(query)
}

It is only possible to have HealthKit sort the results by date currently. You should file a bug with Apple for the enhancement that you'd like.

Related

how to fetch N most recent items but sort them in ascending order using NSFetchRequest

I am trying to create an NSFetchRequest to fetch the most recent 80 items from my entity and sort them in ascending order.
Is it possible to achieve this in one request? Currently I am doing two requests. One to get the date of the most recent item offset by 80 and then using that date in the second request.
What I want to achieve is:
let request:NSFetchRequest<Item> = Item.fetchRequest()
let sort = NSSortDescriptor(key: "itemTimestamp", ascending: false)
request.sortDescriptors = [sort]
request.predicate = NSPredicate(format: "itemGroupId == %#", self.itemGroupId)
request.fetchLimit = 80
// add logic to sort the returned results in ascending: true

in Swift/ CloudKit, what is the proper syntax for creating NSPredicate to search for double

Would any please help me understand what I'm doing wrong? I am trying to use Cloudkit's NSPredicate to search for a Double value in the cloudkit DB and I'm not getting any results. No records come back when I know there should be some. I feel that my syntax may be off. Any advice is welcome.
let val1: NSNumber = 5.4
let predicate2 = NSPredicate(format: "monday_start == %f", val1 )
let sort = NSSortDescriptor(key: "creationDate", ascending: false)
let combinedQuery = NSCompoundPredicate(andPredicateWithSubpredicates: [predicate2])

How to use NSFetchedResultsController to return total of a relationship property given a predicate

I'm writing an expense tracker app and this is my data model:
In one screen where I show a periodic (e.g. daily) summary of expenses, I want to use an NSFetchedResultsController to fetch all the categories and the totals of their expenses for every single period (e.g. every day). A period is defined by two NSDate variables--a startDate and an endDate, because I will have weekly and monthly views, too--which I think should be dependent on the index of the summary in the NSFetchedResultsController. I also want the NSFetchedResultsController to return the category even if the sum is zero. I don't know how to set this up.
What I've tried: I've successfully built an NSFetchedResultsController on my Category entity and used an NSExpressionDescription to get the total of its expenses relationship, but it totals all expenses and I can't find a way to specify an inclusive period.
let request = NSFetchRequest(entityName: Category.entityName)
request.resultType = .DictionaryResultType
request.propertiesToFetch = [
"name", "color",
{
let totalColumn = NSExpressionDescription()
totalColumn.name = "total"
totalColumn.expression = NSExpression(format: "#sum.expenses.amount")
totalColumn.expressionResultType = .DecimalAttributeType
return totalColumn
}()
]
request.sortDescriptors = [NSSortDescriptor(key: "name", ascending: true)]
let fetcher = NSFetchedResultsController(fetchRequest: request, managedObjectContext: App.state.mainQueueContext, sectionNameKeyPath: nil, cacheName: nil)
I've also been reading about fetched properties, but I also can't find a way to indicate the startDate and endDate in the predicate before the NSFetchedResultsController fires the fetch. Help?
You can add a predicate to your fetch request:
request.predicate = [NSPredicate predicateWithFormat:#"(date >= %#) AND (date <= %#)", startDate, endDate];

NSPredicate equals nil in NSFetchRequest

I want to fetch object from Core Data using NSPredicate. I made it, but when I launch NSFetchRequest the NSPredicate equals nil shown in the console. I have the Xcode 6.4, Swift 1.2. I restarted Xcode but I get the same result. How can I make it?
func fetchRequest() -> NSFetchRequest {
let fetchRequest = NSFetchRequest(entityName: "Car")
let sortDescriptor = NSSortDescriptor(key: "personCar", ascending: true)
fetchRequest.predicate = NSPredicate(format: "personRelationship.namePerson contains[c] %#", currentPerson)
fetchRequest.fetchBatchSize = 50
fetchRequest.sortDescriptors = [sortDescriptor]
println(fetchRequest)
return fetchRequest
}
The message from the console
<NSFetchRequest: 0x1700db040> (entity: Car; predicate: ((null)); sortDescriptors: ((
"(personCar, ascending, compare:)"
)); batch size: 50; type: NSManagedObjectResultType; )
Make sure that your fetchRequest.predicate value is set (i.e., is not nil).
The code in your post does show that the predicate value is assigned. However, when the NSFetchRequest.predicate attribute is not set then the println console message will display ((null)) for the predicate value.

Setting NSPredicate in Swift CoreData

Am Rewriting my existing objective c code(ios) to swift and now am facing some issues with Coredata NSPredicate in swift as there is some many to one relationships and vice-versa.. am using the following code,
let fetchRequest = NSFetchRequest(entityName: "TUMessage")
let sortSequence = NSSortDescriptor(key: "sequence", ascending: true)
let sortTime = NSSortDescriptor(key: "epoch_time", ascending: true)
var filterPredicate:NSPredicate = NSPredicate(format:"thread == [c] %#",contact.threads.anyObject())
 fetchRequest.predicate = filterPredicate
var sortDescriptor:NSArray = NSArray(objects: sortTime,sortSequence)
fetchRequest.sortDescriptors = sortDescriptor
fetchRequest.fetchBatchSize = 50
return fetchRequest
where "TUMessage" is the table we need to fetch data from, "sequence" for sorting the fetched result, "thread == [c] %#" is a relationship of message table (many to one since each contact have multiple thread) ,
and contact.threads.anyObject() is the predicate which am trying to add.Unfortunately am getting the following error
type anyobject? does not confirm to protocol, CVarArgType
Any help would be appreciated..
Thank you
You need to unwrap it and cast to the specific class
contact.threads.anyObject()! as MYClass

Resources