コード例 #1
0
        // returns:  A 'condition cell', which displays information about the condition.
        UITableViewCell GetConditionCell(UITableView tableView, NSIndexPath indexPath)
        {
            var         cell      = (ConditionCell)tableView.DequeueReusableCell(ConditionCell);
            NSPredicate condition = EventTriggerCreator.Conditions [indexPath.Row];

            var hkCondition = condition.HomeKitConditionType();

            switch (hkCondition.Type)
            {
            case HomeKitConditionType.Characteristic:
                cell.SetCharacteristic(hkCondition.CharacteristicData.Item1, (NSNumber)hkCondition.CharacteristicData.Item2);
                break;

            case HomeKitConditionType.ExactTime:
                cell.SetOrder(hkCondition.ExactTimeData.Item1, hkCondition.ExactTimeData.Item2);
                break;

            case HomeKitConditionType.SunTime:
                cell.SetOrder(hkCondition.SunTimeData.Item1, hkCondition.SunTimeData.Item2);
                break;

            case HomeKitConditionType.Unknown:
                cell.SetUnknown();
                break;
            }

            return(cell);
        }
コード例 #2
0
    private void CreateSubscription()
    {
        var database  = CKContainer.DefaultContainer().PrivateCloudDatabase;
        var predicate = NSPredicate.PredicateWithValue(true);

        var notificationInfo = new CKNotificationInfo();

        var querySubscription = new CKQuerySubscription(
            recordType,
            predicate,
            CKQuerySubscriptionOptions.FiresOnRecordCreation |
            CKQuerySubscriptionOptions.FiresOnRecordDeletion |
            CKQuerySubscriptionOptions.FiresOnRecordUpdate);

        querySubscription.NotificationInfo = notificationInfo;

        database.SaveSubscription(querySubscription, OnSubscriptionSaved);

        //alternatively...you can use a CKModifySubscriptionsOperation

        //var op = new CKModifySubscriptionsOperation(new[] { querySubscription }, null);
        //op.Configuration.QualityOfService = NSQualityOfService.UserInitiated;
        //op.ModifySubscriptionsCompletionBlock = OnSubscriptionModified;
        //database.AddOperation(op);
    }
コード例 #3
0
        private void ShowPicker(NSObject sender)
        {
            // This example is to be run on iOS 8.0.
            if (!DeviceHelper.IsRunningOn8())
            {
                return;
            }

            ABPeoplePickerNavigationController picker = new ABPeoplePickerNavigationController();

            picker.SelectPerson2  += HandleSelectPerson2;
            picker.PerformAction2 += HandlePerformAction2;
            picker.Cancelled      += HandleCancelled;

            // The people picker will only display the person's name, image and email properties in ABPersonViewController.
            picker.DisplayedProperties.Add(ABPersonProperty.Email);

            // The people picker will enable selection of persons that have at least one email address.
            picker.PredicateForEnablingPerson = NSPredicate.FromFormat("emailAddresses.@count > 0");

            // The people picker will select a person that has exactly one email address and call HandleSelectPerson2,
            // otherwise the people picker will present an ABPersonViewController for the user to pick one of the email addresses.
            picker.PredicateForSelectionOfPerson = NSPredicate.FromFormat("emailAddresses.@count = 1");

            PresentViewController(picker, true, null);
        }
コード例 #4
0
        public void FetchRecords(string recordType, Action <List <CKRecord> > completionHandler)
        {
            var truePredicate = NSPredicate.FromValue(true);
            var query         = new CKQuery(recordType, truePredicate)
            {
                SortDescriptors = new [] { new NSSortDescriptor("creationDate", false) }
            };

            var queryOperation = new CKQueryOperation(query)
            {
                DesiredKeys = new [] { NameField }
            };

            var results = new List <CKRecord> ();

            queryOperation.RecordFetched = (record) => results.Add(record);

            queryOperation.Completed = (cursor, error) => {
                if (error != null)
                {
                    Console.WriteLine("An error occured: {0}", error.Description);
                    return;
                }

                InvokeOnMainThread(() => completionHandler(results));
            };

            publicDatabase.AddOperation(queryOperation);
        }
コード例 #5
0
        public void Subscribe()
        {
            if (Subscribed)
            {
                return;
            }

            var truePredicate    = NSPredicate.FromValue(true);
            var itemSubscription = new CKSubscription(ItemRecordType, truePredicate, CKSubscriptionOptions.FiresOnRecordCreation);

            var notification = new CKNotificationInfo {
                AlertBody = "New Item Added",
                ShouldSendContentAvailable = true
            };

            itemSubscription.NotificationInfo = notification;

            publicDatabase.SaveSubscription(itemSubscription, (sub, error) => {
                if (error != null)
                {
                    Console.WriteLine("An error occured: {0}", error.LocalizedDescription);
                    return;
                }

                Console.WriteLine("Subscribed to Item");
                var defaults = NSUserDefaults.StandardUserDefaults;
                defaults.SetBool(true, "subscribed");
                defaults.SetString(sub.SubscriptionId, "subscriptionID");
            });
        }
コード例 #6
0
        static void DeleteUnregisteredEvent(List <Calendar> events)
        {
            NSDate      startDate = DateTimeToNSDate(DateTime.Now).AddSeconds(-(3600 * 2));
            NSDate      endDate   = DateTimeToNSDate(DateTime.Now.AddMonths(1)).AddSeconds(-(3600 * 2));
            NSPredicate query     = EventStore.PredicateForEvents(startDate, endDate, new [] { Calendar });

            EKEvent[] queryresult = EventStore.EventsMatching(query);
            if (queryresult == null)
            {
                return;
            }
            EKEvent[] todelete = Array.FindAll(queryresult, x => {
                foreach (var item in events)
                {
                    if (item.EventKitID == x.EventIdentifier || x.StartDate.SecondsSinceReferenceDate < NSDate.Now.SecondsSinceReferenceDate)
                    {
                        return(false);
                    }
                }
                return(true);
            });

            NSError err;
            bool    succes;

            foreach (var item in todelete)
            {
                succes = EventStore.RemoveEvent(item, EKSpan.ThisEvent, true, out err);
                if (!succes)
                {
                    throw new Exception("Delete failed");
                }
            }
        }
コード例 #7
0
 public void SetUp()
 {
     TestRuntime.AssertXcodeVersion(6, 0);
     TestRuntime.AssertSystemVersion(ApplePlatform.MacOSX, 10, 10, throwIfOtherPlatform: false);
     q  = new CKQuery("Foo", NSPredicate.FromFormat("email = '@xamarin'"));
     op = new CKQueryOperation(q);
 }
コード例 #8
0
    private void RunQuery()
    {
        // The objective-c version takes a format string and a variadic argument
        // list for substititon, but we only support sending an unformatted string
        // down. Marshalling variadic arguments is tricky....
        // Just do your formatting on the C# side.

        // Note that passing a bad predicate string will throw an exception

        // Pick a random name out of the hat
        var queryStr = string.Format("name = '{0}'", names[UnityEngine.Random.Range(0, names.Length)]);

        Debug.Log(string.Format("Running query with predicate ({0})", queryStr));

        // Queries are made with NSPredicate which sorta like SQL and sorta
        // like regular expressions.
        // See https://nshipster.com/nspredicate/ for a quick intro to the kinds
        // of queries you can run. Were just going to do a simple key,value search
        CKQuery query = new CKQuery("Person", NSPredicate.PredicateWithFormat(queryStr));

        // The second argument here is the container to search in. Unless you
        // are using custom containers, you'll want to pass null for the
        // default container

        database.PerformQuery(query, null, OnQueryComplete);
    }
コード例 #9
0
        public static EKEvent[] FetchEvents(DateTime startDate, DateTime endDate)
        {
            // Create the predicate. Pass it the default calendar.
            //Util.WriteLine ("Getting Calendars");
            EKEventStore store = new EKEventStore();
//			store.RequestAccess (EKEntityType.Event, (bool granted, NSError e) => {
//				if (granted)
//				{
//#if DEBUG
//					Console.WriteLine("Access Granted!");
//#endif
//					//Do add events calendars and any calendar stuff here
//				}
//				else
//					new UIAlertView ( "Access Denied", "User Denied Access to Calendar Data", null, "ok", null).Show ();
//			}
//			);
            var calendarArray = store.Calendars;
            //Util.WriteLine ("Predicate");
            //Convert to NSDate
            NSDate      nstartDate = startDate.DateTimeToNSDate();
            NSDate      nendDate   = endDate.DateTimeToNSDate();
            NSPredicate predicate  = store.PredicateForEvents(nstartDate, nendDate, calendarArray);

            //Util.WriteLine ("Fetching Events");
            // Fetch all events that match the predicate.
            var eventsArray = store.EventsMatching(predicate);

            //Util.WriteLine ("Returning results");
            if (eventsArray == null)
            {
                eventsArray = new List <EKEvent> ().ToArray();
            }
            return(eventsArray);
        }
コード例 #10
0
        private Task InstigateDocumentLookupAsync(TaskScheduler synchronizationContextTaskScheduler) =>
        Task.Factory.StartNew(
            () =>
        {
            var query = new NSMetadataQuery
            {
                SearchScopes = new NSObject[]
                {
                    NSMetadataQuery.UbiquitousDocumentsScope
                },
                Predicate = NSPredicate.FromFormat(
                    "%K == %@",
                    new NSObject[]
                {
                    NSMetadataQuery.ItemFSNameKey,
                    new NSString(documentFilename)
                })
            };

            NSNotificationCenter.DefaultCenter.AddObserver(NSMetadataQuery.DidFinishGatheringNotification, this.OnQueryFinished, query);
            query.StartQuery();
        },
            CancellationToken.None,
            TaskCreationOptions.None,
            synchronizationContextTaskScheduler);
コード例 #11
0
        public void QueryForRecords(string referenceRecordName, Action <List <CKRecord> > completionHandler)
        {
            var recordId = new CKRecordID(referenceRecordName);
            var parent   = new CKReference(recordId, CKReferenceAction.None);

            var predicate = NSPredicate.FromFormat("parent == %@", parent);
            var query     = new CKQuery(ReferenceSubItemsRecordType, predicate)
            {
                SortDescriptors = new [] { new NSSortDescriptor("creationDate", false) }
            };

            var queryOperation = new CKQueryOperation(query)
            {
                DesiredKeys = new [] { NameField }
            };

            var results = new List <CKRecord> ();

            queryOperation.RecordFetched = (record) => results.Add(record);

            queryOperation.Completed = (cursor, error) => {
                if (error != null)
                {
                    Console.WriteLine("An error occured: {0}", error.Description);
                    return;
                }

                DispatchQueue.MainQueue.DispatchAsync(() => completionHandler(results));
            };

            publicDatabase.AddOperation(queryOperation);
        }
コード例 #12
0
        public void QueryForRecords(CLLocation location, Action <List <CKRecord> > completionHandler)
        {
            var radiusInKilometers = NSNumber.FromFloat(5f);
            var predicate          = NSPredicate.FromFormat("distanceToLocation:fromLocation:(location, %@) < %f",
                                                            new NSObject[] { location, radiusInKilometers });

            var query = new CKQuery(ItemRecordType, predicate)
            {
                SortDescriptors = new [] { new NSSortDescriptor("creationDate", false) }
            };

            var queryOperation = new CKQueryOperation(query)
            {
                DesiredKeys = new [] { NameField }
            };

            var results = new List <CKRecord> ();

            queryOperation.RecordFetched = (record) => results.Add(record);

            queryOperation.Completed = (cursor, error) => {
                if (error != null)
                {
                    Console.WriteLine("An error occured: {0}", error.Description);
                    return;
                }

                DispatchQueue.MainQueue.DispatchAsync(() => completionHandler(results));
            };

            publicDatabase.AddOperation(queryOperation);
        }
コード例 #13
0
        /// <summary>
        /// Starts a query to look for the sample Test File.
        /// </summary>
        private void FindDocument()
        {
            Console.WriteLine("Finding Document...");

            // Create a new query and set it's scope
            Query = new NSMetadataQuery();
            Query.SearchScopes = new NSObject [] {
                NSMetadataQuery.UbiquitousDocumentsScope,
                NSMetadataQuery.UbiquitousDataScope,
                NSMetadataQuery.AccessibleUbiquitousExternalDocumentsScope
            };

            // Build a predicate to locate the file by name and attach it to the query
            var pred = NSPredicate.FromFormat("%K == %@"
                                              , new NSObject[] {
                NSMetadataQuery.ItemFSNameKey
                , new NSString(TestFilename)
            });

            Query.Predicate = pred;

            // Register a notification for when the query returns
            NSNotificationCenter.DefaultCenter.AddObserver(this
                                                           , new Selector("queryDidFinishGathering:")
                                                           , NSMetadataQuery.DidFinishGatheringNotification
                                                           , Query);

            // Start looking for the file
            Query.StartQuery();
            Console.WriteLine("Querying: {0}", Query.IsGathering);
        }
コード例 #14
0
        /// <summary>
        /// Event for adding a contact from the contact book
        /// </summary>
        private void AddRecipientFromContactButton_TouchUpInside(object sender, EventArgs e)
        {
            _isComeFromContact = true;

            if (contactPickerView == null)
            {
                contactPickerView = new CNContactPickerViewController();
                contactPickerView.DisplayedPropertyKeys          = new NSString[] { CNContactKey.EmailAddresses };
                contactPickerView.PredicateForEnablingContact    = NSPredicate.FromFormat("emailAddresses.@count > 0");
                contactPickerView.PredicateForSelectionOfContact = NSPredicate.FromFormat("emailAddresses.@count == 1");

                var contactPickerDelegate = new ContactPickerDelegate();
                contactPickerView.Delegate = contactPickerDelegate;
                contactPickerDelegate.SelectionCanceled       += () => { };
                contactPickerDelegate.ContactPropertySelected += (property) => { };


                contactPickerDelegate.ContactsSelected += (CNContactPickerViewController picker, CNContact[] contacts) =>
                {
                    foreach (var contact in contacts)
                    {
                        if (App.Locator.Alert.LsRecipients.Any((arg) => arg.Email.ToLower() == contact.EmailAddresses[0].Value.ToString().Trim().ToLower()))
                        {
                            continue;
                        }
                        var recipient = new AlertRecipientDTO();
                        recipient.DisplayName = string.Format("{0} {1}", contact.GivenName, contact.FamilyName);
                        recipient.Email       = contact.EmailAddresses[0].Value.ToString().Trim();
                        AddRecipientToRecipientContainer(recipient);
                    }
                };
            }

            PresentViewController(contactPickerView, true, null);
        }
コード例 #15
0
        void ShowPicker(NSObject sender)
        {
            ABPeoplePickerNavigationController picker = new ABPeoplePickerNavigationController();

            picker.SelectPerson   += HandleSelectPerson;
            picker.SelectPerson2  += HandleSelectPerson2;
            picker.PerformAction  += HandlePerformAction;
            picker.PerformAction2 += HandlePerformAction2;
            picker.Cancelled      += HandleCancelled;

            // The people picker will only display the person's name, image and email properties in ABPersonViewController.
            picker.DisplayedProperties.Add(ABPersonProperty.Email);

            // The people picker will enable selection of persons that have at least one email address.
            if (picker.RespondsToSelector(new Selector("setPredicateForEnablingPerson:")))
            {
                picker.PredicateForEnablingPerson = NSPredicate.FromFormat("emailAddresses.@count > 0");
            }

            // The people picker will select a person that has exactly one email address and call peoplePickerNavigationController:didSelectPerson:,
            // otherwise the people picker will present an ABPersonViewController for the user to pick one of the email addresses.
            if (picker.RespondsToSelector(new Selector("setPredicateForSelectionOfPerson:")))
            {
                picker.PredicateForSelectionOfPerson = NSPredicate.FromFormat("emailAddresses.@count = 1");
            }

            PresentViewController(picker, true, null);
        }
コード例 #16
0
        public static PredicateData GetPredicateData(this NSPredicate predicate)
        {
            var predicateString = predicate.PredicateFormat;

            var predicateData = new PredicateData(predicateString);

            foreach (var operatorString in operatorStrings)
            {
                var paddedOperatorString = string.Format($" {operatorString} ");

                var index = predicateString.LastIndexOf(paddedOperatorString, StringComparison.Ordinal);

                if (index > 0)
                {
                    predicateData.KeyString = predicateString.Substring(0, index);

                    predicateData.ValueString = predicateString
                                                .Substring(index + paddedOperatorString.Length)?
                                                .Replace("\"", string.Empty);

                    predicateData.OperatorString = operatorString.Replace("==", "=");

                    return(predicateData);
                }
            }

            return(predicateData);
        }
コード例 #17
0
		public static Photographer WithName(string name, NSManagedObjectContext context)
		{
			Photographer photographer = null;
			// This is just like Photo(Flickr)'s method.  Look there for commentary.
			if (name.Length > 0)
			{
				var request = new NSFetchRequest("Photographer")
				{
					SortDescriptors = new[] {new NSSortDescriptor("name", true, new Selector("localizedCaseInsensitiveCompare:"))},
					Predicate =  NSPredicate.FromFormat("name = %@", new NSObject[] {(NSString) name})
				};
				NSError error;
				var matches = context.ExecuteFetchRequest(request, out error);
				if (matches == null || matches.Length > 1)
				{
					// handle error
				}
				else if (matches.Length == 0)
				{
					photographer = InsertNewObject(context);
					photographer.Name = name;
				}
				else
				{
					photographer = (Photographer) matches.First();
				}
			}
			return photographer;
		}
コード例 #18
0
 static void SelectUnregisteredEvents(List <Calendar> events)
 {
     foreach (var item in events)
     {
         NSDate      startDate   = DateTimeToNSDate(item.Start).AddSeconds(-(3600 * 2));
         NSDate      endDate     = DateTimeToNSDate(item.End).AddSeconds(-(3600 * 2));
         NSPredicate query       = EventStore.PredicateForEvents(startDate, endDate, new [] { Calendar });
         EKEvent[]   queryresult = EventStore.EventsMatching(query);
         bool        exist       = false;
         if (queryresult == null)
         {
             item.RegisterEventForStoring = true;
             continue;
         }
         foreach (var evt in queryresult)
         {
             if (evt.Location == (item.Room.Code ?? String.Empty) && evt.Title == item.ActiTitle)
             {
                 exist           = true;
                 item.EventKitID = evt.EventIdentifier;
             }
         }
         item.RegisterEventForStoring |= !exist;
     }
 }
コード例 #19
0
ファイル: CNContactStore.cs プロジェクト: artemy0/Quiz
        /// <summary>
        /// Fetches all unified contacts matching the specified predicate.
        /// </summary>
        /// <returns>The contacts matching predicate.</returns>
        /// <param name="predicate">Predicate.</param>
        /// <param name="keys">Keys.</param>
        /// <param name="error">Error.</param>
        public NSArray <CNContact> UnifiedContactsMatchingPredicate(NSPredicate predicate, NSArray <NSString> keys, out NSError error)
        {
            Util.NullArgumentTest(predicate);
            Util.NullArgumentTest(keys);

            IntPtr errorPtr    = new IntPtr();
            var    contactsPtr = C.CNContactStore_unifiedContactsMatchingPredicate(
                SelfPtr(),
                predicate.ToPointer(),
                keys.ToPointer(),
                ref errorPtr);

            error = null;
            if (PInvokeUtil.IsNotNull(errorPtr))
            {
                error = new NSError(errorPtr);
                CFFunctions.CFRelease(errorPtr);
            }

            NSArray <CNContact> contacts = null;

            if (PInvokeUtil.IsNotNull(contactsPtr))
            {
                contacts = new NSArray <CNContact>(contactsPtr);
                CFFunctions.CFRelease(contactsPtr);
            }

            return(contacts);
        }
コード例 #20
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="email_address"></param>
        /// <returns></returns>
        public static bool ValidateEmail(string email_address)
        {
            var _regex = "[A-Z0-9a-z._%+-]+@[A-Za-z0-9.-]+\\.[A-Za-z]{2,4}";

            var _tester = NSPredicate.FromFormat(String.Format("SELF MATCHES {0}", _regex));

            return(_tester.EvaluateWithObject(NSObject.FromObject(email_address)));
        }
コード例 #21
0
    public void Cant_create_CKQuery_with_no_predicate()
    {
        NSPredicate predicate = null;

        TestDelegate sut = () => new CKQuery("record_type", predicate);

        Assert.Throws <CloudKitException>(sut);
    }
コード例 #22
0
        /// <summary>
        ///
        /// </summary>
        /// <param name="password"></param>
        /// <returns></returns>
        public static bool ValidatePassword(string password)
        {
            var _regex = "^(?=.*[A-Za-z])(?=.*\\d)[A-Za-z\\d]{6,}$";

            var _tester = NSPredicate.FromFormat(String.Format("SELF MATCHES {0}", NSObject.FromObject(_regex)));

            return(_tester.EvaluateWithObject(NSObject.FromObject(password)));
        }
コード例 #23
0
        private void HandleContactsWithProfilePicture()
        {
            var picker = this.CreatePicker();

            // Only show contacts with email addresses.
            picker.PredicateForEnablingContact = NSPredicate.FromFormat("imageDataAvailable == true");
            base.NavigationController.PresentViewController(picker, true, null);
        }
コード例 #24
0
        private void HandleContactsWithEmailAddresses()
        {
            var picker = this.CreatePicker();

            // Only show contacts with email addresses.
            picker.PredicateForEnablingContact = NSPredicate.FromFormat("emailAddresses.@count > 0");
            base.NavigationController.PresentViewController(picker, true, null);
        }
コード例 #25
0
        /// <summary>
        /// Removes all reminders.
        /// </summary>
        public static void RemoveAllReminders()
        {
            object[] calenderArray = new object[1];
            calenderArray[0] = eventStore.defaultCalendarForNewReminders;

            NSPredicate predicate = eventStore.Predicate(calenderArray);

            eventStore.FetchRemindersMatchingPredicate(predicate, _removeReminders);
        }
コード例 #26
0
        string GetUrlScheme(SocialNetworks socialNetwork)
        {
            var predicate    = NSPredicate.FromFormat("%K = %@", new NSObject[] { new NSString("CFBundleURLName"), new NSString(socialNetwork.ToString()) });
            var urlTypes     = (NSMutableArray)NSBundle.MainBundle.InfoDictionary.ObjectForKey(new NSString("CFBundleURLTypes"));
            var urlSchemes   = (NSArray)urlTypes.Filter(predicate).ValueForKey(new NSString("CFBundleURLSchemes"));
            var neededScheme = urlSchemes.GetItem <NSMutableArray>(0).GetItem <NSMutableString>(0).ToString();

            return(neededScheme);
        }
コード例 #27
0
    public void Can_create_CKQuery()
    {
        var recordType = "record_type";
        var predicate  = NSPredicate.PredicateWithValue(false);
        var query      = new CKQuery(recordType, predicate);

        Assert.AreEqual(query.RecordType, recordType);
        Assert.AreEqual(query.Predicate, predicate);
    }
コード例 #28
0
        // Removes a predicate from the pending conditions.
        public void RemoveCondition(NSPredicate predicate)
        {
            var index = Conditions.IndexOf(predicate);

            if (index >= 0)
            {
                Conditions.RemoveAt(index);
            }
        }
コード例 #29
0
        private void SelectContactButton_TouchUpInside(object sender, EventArgs e)
        {
            // Create a new picker
            var picker = new CNContactPickerViewController();

            // A contact has many properties (email, phone numbers, birthday)
            // and you must specify which properties you want to fetch,
            // in this case PhoneNumbers
            picker.DisplayedPropertyKeys          = new NSString[] { CNContactKey.PhoneNumbers };
            picker.PredicateForEnablingContact    = NSPredicate.FromValue(true);
            picker.PredicateForSelectionOfContact = NSPredicate.FromValue(true);

            // Respond to selection
            var pickerDelegate = new ContactPickerDelegate();

            picker.Delegate = pickerDelegate;

            // If the user cancels the contact selection,
            // show an empty string
            pickerDelegate.SelectionCanceled += () => {
                this.SelectedContactField.Text = "";
            };

            // If the user selects a contact,
            // show the full name
            pickerDelegate.ContactSelected += (contact) => {
                this.SelectedContactField.Text = $"{contact.GivenName} {contact.FamilyName}";

                // If the contact has phone numbers
                if (contact.PhoneNumbers != null)
                {
                    // Query for mobile only
                    // Each PhoneNumber has a label with a description
                    // and a Value with the actual phone number
                    // exposed by the StringValue property
                    var mobilePhone = contact.PhoneNumbers.
                                      Where(p => p.Label.Contains("Mobile")).
                                      Select(p => p.Value.StringValue);

                    // If at least one mobile phone number
                    if (mobilePhone != null)
                    {
                        // Generate a new data source
                        var tblSource = new TableSource(mobilePhone.ToArray(), this);
                        // and perform data-binding
                        this.TableView.Source = tblSource;
                    }
                }
            };

            pickerDelegate.ContactPropertySelected += (property) => {
                this.SelectedContactField.Text = property.Value.ToString();
            };

            // Display picker
            PresentViewController(picker, true, null);
        }
コード例 #30
0
        private void HandleContactsWithPhoneNumbers()
        {
            var picker = new CNContactPickerViewController {
                Delegate = this
            };

            // Only show contacts with email addresses.
            picker.PredicateForSelectionOfProperty = NSPredicate.FromFormat("key == 'phoneNumbers'");
            base.NavigationController.PresentViewController(picker, true, null);
        }
コード例 #31
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;	
		}
コード例 #32
0
		// Removes a predicate from the pending conditions.
		public void RemoveCondition (NSPredicate predicate)
		{
			var index = Conditions.IndexOf (predicate);
			if (index >= 0)
				Conditions.RemoveAt (index);
		}
コード例 #33
0
		// Adds a predicate to the pending conditions.
		public void AddCondition (NSPredicate predicate)
		{
			Conditions.Add (predicate);
		}
コード例 #34
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 ();
		}
コード例 #35
0
		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;
		}
コード例 #36
0
		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;
		}