コード例 #1
0
        private List <Product> PerformSearch_Swift(string[] searchItems)
        {
            // Update the filtered array based on the search text.
            var searchResults = this.products;

            // Build all the "AND" expressions for each value in searchString.
            var andMatchPredicates = searchItems.Select(searchItem => FindMatches(searchItem)).ToArray();

            // Match up the fields of the Product object.
            var finalCompoundPredicate = NSCompoundPredicate.CreateAndPredicate(andMatchPredicates);
            var filteredResults        = searchResults.Where(searchResult => finalCompoundPredicate.EvaluateWithObject(searchResult));

            return(filteredResults.ToList());
        }
コード例 #2
0
        private void StartQuery(HKQuantityTypeIdentifier quantityTypeIdentifier, NSDate startDate, HKAnchoredObjectUpdateHandler handler)
        {
            var datePredicate   = HKQuery.GetPredicateForSamples(startDate, null, HKQueryOptions.StrictStartDate);
            var devicePredicate = HKQuery.GetPredicateForObjectsFromDevices(new NSSet <HKDevice>(HKDevice.LocalDevice));
            var queryPredicate  = NSCompoundPredicate.CreateAndPredicate(new NSPredicate[] { datePredicate, devicePredicate });

            var quantityType = HKQuantityType.Create(quantityTypeIdentifier);
            var query        = new HKAnchoredObjectQuery(quantityType, queryPredicate, null, HKSampleQuery.NoLimit, handler);

            query.UpdateHandler = handler;
            this.healthStore.ExecuteQuery(query);

            this.activeDataQueries.Add(query);
        }
コード例 #3
0
ファイル: PostManager.cs プロジェクト: zain-tariq/ios-samples
        NSPredicate CreateLoadNewPostPredicate()
        {
            var len           = tagArray.Length + 1;
            var subPredicates = new NSPredicate[len];

            subPredicates [0] = Utils.CreateAfterPredicate(lastPostSeenOnServer.PostRecord.CreationDate);

            for (int i = 0; i < tagArray.Length; i++)
            {
                subPredicates [i + 1] = Utils.CreateTagPredicate(tagArray [i]);
            }

            // ANDs all subpredicates to make a final predicate
            NSPredicate finalPredicate = NSCompoundPredicate.CreateAndPredicate(subPredicates);

            return(finalPredicate);
        }
コード例 #4
0
        // -------------------------------------------------------------------------------
        //	spotlightFriendlyPredicate:predicate
        //
        //	This method will "clean up" an NSPredicate to make it ready for Spotlight, or return nil if the predicate can't be cleaned.
        //
        //	Foundation's Spotlight support in NSMetdataQuery places the following requirements on an NSPredicate:
        //		- Value-type (always YES or NO) predicates are not allowed
        //		- Any compound predicate (other than NOT) must have at least two subpredicates
        // -------------------------------------------------------------------------------
        private NSPredicate spotlightFriendlyPredicate(NSPredicate predicate)
        {
            if (predicate.Equals(NSPredicate.FromValue(true)) || predicate.Equals(NSPredicate.FromValue(false)))
            {
                return(null);
            }

            if (predicate is NSCompoundPredicate)
            {
                NSCompoundPredicate     compoundPredicate = predicate as NSCompoundPredicate;
                NSCompoundPredicateType type = compoundPredicate.Type;

                List <NSPredicate> cleanSubPredicates = new List <NSPredicate> ();

                foreach (var dirtySubpredicate in compoundPredicate.Subpredicates)
                {
                    NSPredicate cleanSubPredicate = this.spotlightFriendlyPredicate(dirtySubpredicate);
                    if (cleanSubPredicate != null)
                    {
                        cleanSubPredicates.Add(cleanSubPredicate);
                    }
                }

                if (cleanSubPredicates.Count == 0)
                {
                    return(null);
                }

                if (cleanSubPredicates.Count == 1 && type != NSCompoundPredicateType.Not)
                {
                    return(cleanSubPredicates.First());
                }
                else
                {
                    return(new NSCompoundPredicate(type, cleanSubPredicates.ToArray()));
                }
            }
            else
            {
                return(predicate);
            }
        }
コード例 #5
0
ファイル: PostManager.cs プロジェクト: zain-tariq/ios-samples
        CKQuery CreatePostQuery()
        {
            // Create predicate out of tags. If self.tagArray is empty we should get every post
            NSPredicate[] subPredicates = new NSPredicate[tagArray.Length];
            for (int i = 0; i < tagArray.Length; i++)
            {
                subPredicates [i] = Utils.CreateTagPredicate(tagArray [i]);
            }

            // If our tagArray is empty, create a true predicate (as opposed to a predicate containing "Tags CONTAINS ''"
            NSPredicate finalPredicate = tagArray.Length == 0
                                ? NSPredicate.FromValue(true)
                                : NSCompoundPredicate.CreateAndPredicate(subPredicates);

            CKQuery postQuery = new CKQuery(Post.RecordType, finalPredicate);

            // lastest post on the top
            postQuery.SortDescriptors = Utils.CreateCreationDateDescriptor(ascending: false);

            return(postQuery);
        }
コード例 #6
0
        private void createNewSearchForPredicate(NSPredicate predicate, string title)
        {
            if (predicate == null)
            {
                return;
            }

            // remove the old search results.
            mySearchResults.Remove(mySearchResults.ArrangedObjects());

            // always search for items in the Address Book
            //NSPredicate addrBookPredicate = NSPredicate.FromFormat (" (kMDItemKind == 'Address Book Person Data')",new NSObject[0]);
            NSPredicate addrBookPredicate = NSPredicate.FromFormat(" (kMDItemContentType == 'com.apple.addressbook.person')", new NSObject[0]);

            predicate = NSCompoundPredicate.CreateAndPredicate(new NSPredicate[2] {
                addrBookPredicate, predicate
            });

            // set the query predicate....
            query.Predicate = predicate;

            // and send it off for processing...
            query.StartQuery();
        }
コード例 #7
0
        private NSCompoundPredicate FindMatches(string searchString)
        {
            /*
             * Each searchString creates an OR predicate for: name, yearIntroduced, introPrice.
             * Example if searchItems contains "Gladiolus 51.99 2001":
             * - name CONTAINS[c] "gladiolus"
             * - name CONTAINS[c] "gladiolus", yearIntroduced ==[c] 2001, introPrice ==[c] 51.99
             * - name CONTAINS[c] "ginger", yearIntroduced ==[c] 2007, introPrice ==[c] 49.98
             */
            var searchItemsPredicate = new List <NSPredicate>();

            /*
             * Below we use NSExpression represent expressions in our predicates.
             * NSPredicate is made up of smaller, atomic parts:
             * two NSExpressions (a left-hand value and a right-hand value).
             */

            // Name field matching.
            var titleExpression        = NSExpression.FromKeyPath(ExpressionKeys.Title);
            var searchStringExpression = NSExpression.FromConstant(new NSString(searchString));

            var titleSearchComparisonPredicate = new NSComparisonPredicate(titleExpression,
                                                                           searchStringExpression,
                                                                           NSComparisonPredicateModifier.Direct,
                                                                           NSPredicateOperatorType.Contains,
                                                                           NSComparisonPredicateOptions.CaseInsensitive | NSComparisonPredicateOptions.DiacriticInsensitive);

            searchItemsPredicate.Add(titleSearchComparisonPredicate);

            var numberFormatter = new NSNumberFormatter
            {
                NumberStyle       = NSNumberFormatterStyle.None,
                FormatterBehavior = NSNumberFormatterBehavior.Default
            };

            // The `searchString` may fail to convert to a number.
            var targetNumber = numberFormatter.NumberFromString(searchString);

            if (targetNumber != null)
            {
                // Use `targetNumberExpression` in both the following predicates.
                var targetNumberExpression = NSExpression.FromConstant(targetNumber);

                // The `yearIntroduced` field matching.
                var yearIntroducedExpression = NSExpression.FromKeyPath(ExpressionKeys.YearIntroduced);
                var yearIntroducedPredicate  = new NSComparisonPredicate(yearIntroducedExpression,
                                                                         targetNumberExpression,
                                                                         NSComparisonPredicateModifier.Direct,
                                                                         NSPredicateOperatorType.EqualTo,
                                                                         NSComparisonPredicateOptions.CaseInsensitive | NSComparisonPredicateOptions.DiacriticInsensitive);

                searchItemsPredicate.Add(yearIntroducedPredicate);

                // The `price` field matching.
                var priceExpression = NSExpression.FromKeyPath(ExpressionKeys.IntroPrice);
                var finalPredicate  = new NSComparisonPredicate(priceExpression,
                                                                targetNumberExpression,
                                                                NSComparisonPredicateModifier.Direct,
                                                                NSPredicateOperatorType.EqualTo,
                                                                NSComparisonPredicateOptions.CaseInsensitive | NSComparisonPredicateOptions.DiacriticInsensitive);

                searchItemsPredicate.Add(finalPredicate);
            }

            return(NSCompoundPredicate.CreateOrPredicate(searchItemsPredicate.ToArray()));
        }
コード例 #8
0
 // returns:  The new `NSCompoundPredicate`, generated from the pending conditions.
 protected NSPredicate NewPredicate()
 {
     return(NSCompoundPredicate.CreateAndPredicate(Conditions.ToArray()));
 }
コード例 #9
0
        static NSPredicate ToPredicate(NSObject @object)
        {
            if (@object == NSNumber.FromBoolean(true))
            {
                return(NSPredicate.FromValue(true));
            }

            if (@object == NSNumber.FromBoolean(false))
            {
                return(NSPredicate.FromValue(false));
            }

            if (@object is NSArray == false)
            {
                return(null);
            }

            var array   = (NSArray)@object;
            var objects = SubArray(array);
            var op      = objects[0].ToString();

            if (MGLPredicateOperatorTypesByJSONOperator.TryGetValue(op, out var operatorType))
            {
                NSComparisonPredicateOptions options = 0;

                if (objects.Count > 3)
                {
                    var collatorExpression = SubArray((NSArray)objects[3]);

                    if (collatorExpression.Count != 2)
                    {
                        return(null);
                    }

                    var collator = (NSDictionary)collatorExpression[1];

                    if (false == collator.ContainsKey((NSString)"locale"))
                    {
                        if (collator.ValueForKey((NSString)"case-sensitive") == NSNumber.FromBoolean(false))
                        {
                            options |= NSComparisonPredicateOptions.CaseInsensitive;
                        }

                        if (collator.ValueForKey((NSString)"diacritic-sensitive") == NSNumber.FromBoolean(false))
                        {
                            options |= NSComparisonPredicateOptions.DiacriticInsensitive;
                        }
                    }
                }

                var subexpressions = ToSubexpressions(SubArray(objects, 1));

                return(new NSComparisonPredicate(
                           subexpressions[0],
                           subexpressions[1],
                           NSComparisonPredicateModifier.Direct,
                           operatorType,
                           options
                           ));
            }

            switch (op)
            {
            case "!": {
                var subpredicates = ToSubpredicates(SubArray(objects, 1));
                if (subpredicates.Count > 1)
                {
                    var predicate = NSCompoundPredicate.CreateOrPredicate(subpredicates.ToArray());

                    return(NSCompoundPredicate.CreateNotPredicate(predicate));
                }

                return(NSPredicate.FromValue(true));
            }

            case "all": {
                var subpredicates = ToSubpredicates(SubArray(objects, 1));

                if (subpredicates.Count == 2)
                {
                    if (subpredicates[0] is NSComparisonPredicate leftCondition &&
                        subpredicates[1] is NSComparisonPredicate rightCondition
                        )
                    {
                        NSExpression[] limits = null;
                        NSExpression   leftConditionExpression = null;

                        if (leftCondition.PredicateOperatorType == NSPredicateOperatorType.GreaterThanOrEqualTo &&
                            rightCondition.PredicateOperatorType == NSPredicateOperatorType.LessThanOrEqualTo
                            )
                        {
                            limits = new NSExpression[]
                            {
                                leftCondition.RightExpression,
                                rightCondition.RightExpression
                            };
                            leftConditionExpression = leftCondition.LeftExpression;
                        }
                        else if (leftCondition.PredicateOperatorType == NSPredicateOperatorType.LessThanOrEqualTo &&
                                 rightCondition.PredicateOperatorType ==
                                 NSPredicateOperatorType.LessThanOrEqualTo
                                 )
                        {
                            limits = new NSExpression[]
                            {
                                leftCondition.LeftExpression,
                                rightCondition.RightExpression
                            };
                            leftConditionExpression = leftCondition.RightExpression;
                        }
                        else if (leftCondition.PredicateOperatorType == NSPredicateOperatorType.LessThanOrEqualTo &&
                                 rightCondition.PredicateOperatorType ==
                                 NSPredicateOperatorType.GreaterThanOrEqualTo
                                 )
                        {
                            limits = new NSExpression[]
                            {
                                leftCondition.LeftExpression,
                                rightCondition.LeftExpression
                            };
                            leftConditionExpression = leftCondition.RightExpression;
                        }
                        else if (leftCondition.PredicateOperatorType == NSPredicateOperatorType.GreaterThanOrEqualTo &&
                                 rightCondition.PredicateOperatorType ==
                                 NSPredicateOperatorType.GreaterThanOrEqualTo
                                 )
                        {
                            limits = new NSExpression[]
                            {
                                leftCondition.RightExpression,
                                rightCondition.LeftExpression
                            };
                            leftConditionExpression = leftCondition.LeftExpression;
                        }

                        if (limits != null && leftConditionExpression != null)
                        {
                            return(NSPredicate.FromFormat("%@ BETWEEN %@", leftConditionExpression,
                                                          NSExpression.FromAggregate(limits)));
                        }
                    }
                }

                return(new NSCompoundPredicate(NSCompoundPredicateType.And, subpredicates.ToArray()));
            }

            case "any": {
                var subpredicates = ToSubpredicates(SubArray(objects, 1));

                return(new NSCompoundPredicate(NSCompoundPredicateType.Or, subpredicates.ToArray()));
            }

            default: {
                var expression = ToExpression(array);

                return(new NSComparisonPredicate(
                           expression,
                           NSExpression.FromConstant(NSNumber.FromBoolean(true)),
                           NSComparisonPredicateModifier.Direct,
                           NSPredicateOperatorType.EqualTo,
                           0
                           ));
            }
            }
        }
コード例 #10
0
        public void BeginWorkout(DateTime beginDate)
        {
            // Obtain the `HKObjectType` for active energy burned and the `HKUnit` for kilocalories.
            var activeEnergyType = HKQuantityType.Create(HKQuantityTypeIdentifier.ActiveEnergyBurned);

            if (activeEnergyType == null)
            {
                return;
            }

            var energyUnit = HKUnit.Kilocalorie;

            // Update properties.
            WorkoutBeginDate = beginDate;
            workoutButton.SetTitle("End Workout");

            // Set up a predicate to obtain only samples from the local device starting from `beginDate`.

            var datePredicate = HKQuery.GetPredicateForSamples((NSDate)beginDate, null, HKQueryOptions.None);

            var devices         = new NSSet <HKDevice> (new HKDevice[] { HKDevice.LocalDevice });
            var devicePredicate = HKQuery.GetPredicateForObjectsFromDevices(devices);
            var predicate       = NSCompoundPredicate.CreateAndPredicate(new NSPredicate[] { datePredicate, devicePredicate });

            //Create a results handler to recreate the samples generated by a query of active energy samples so that they can be associated with this app in the move graph.It should be noted that if your app has different heuristics for active energy burned you can generate your own quantities rather than rely on those from the watch.The sum of your sample's quantity values should equal the energy burned value provided for the workout
            Action <List <HKSample> > sampleHandler;

            sampleHandler = (List <HKSample> samples) => {
                DispatchQueue.MainQueue.DispatchAsync(delegate {
                    var accumulatedSamples = new List <HKQuantitySample> ();

                    var initialActivityEnergy = CurrentActiveEnergyQuantity.GetDoubleValue(energyUnit);
                    double accumulatedValue   = initialActivityEnergy;
                    foreach (HKQuantitySample sample in samples)
                    {
                        accumulatedValue = accumulatedValue + sample.Quantity.GetDoubleValue(energyUnit);
                        var ourSample    = HKQuantitySample.FromType(activeEnergyType, sample.Quantity, sample.StartDate, sample.EndDate);
                        accumulatedSamples.Add(ourSample);
                    }

                    // Update the UI.
                    CurrentActiveEnergyQuantity = HKQuantity.FromQuantity(energyUnit, accumulatedValue);
                    activeEnergyBurnedLabel.SetText($"{accumulatedValue}");

                    // Update our samples.
                    ActiveEnergySamples.AddRange(accumulatedSamples);
                });
            };

            // Create a query to report new Active Energy Burned samples to our app.
            var activeEnergyQuery = new HKAnchoredObjectQuery(activeEnergyType, predicate, null, HKSampleQuery.NoLimit, (query, addedObjects, deletedObjects, newAnchor, error) => {
                if (error == null)
                {
                    // NOTE: `deletedObjects` are not considered in the handler as there is no way to delete samples from the watch during a workout
                    ActiveEnergySamples = new List <HKSample>(addedObjects);
                    sampleHandler(ActiveEnergySamples);
                }
                else
                {
                    Console.WriteLine($"An error occured executing the query. In your app, try to handle this gracefully. The error was: {error}.");
                }
            });

            // Assign the same handler to process future samples generated while the query is still active.
            activeEnergyQuery.UpdateHandler = (query, addedObjects, deletedObjects, newAnchor, error) => {
                if (error == null)
                {
                    ActiveEnergySamples = new List <HKSample> (addedObjects);
                    sampleHandler(ActiveEnergySamples);
                }
                else
                {
                    Console.WriteLine($"An error occured executing the query. In your app, try to handle this gracefully. The error was: {error}.");
                }
            };

            // Start Query
            CurrentQuery = activeEnergyQuery;
            HealthStore.ExecuteQuery(activeEnergyQuery);
        }