예제 #1
0
		public override void ViewDidLoad ()
		{
			this.AddOption ("Year", SelectYear);
			this.AddOption ("Month", SelectMonth);
			this.AddOption ("Month Names", SelectMonthNames);
			this.AddOption ("Year Numbers", SelectYearNumbers);
			this.AddOption ("Flow", SelectFlow);
			this.AddOption ("Week view", SelectWeekView);

			base.ViewDidLoad ();

			NSCalendar calendar = new NSCalendar (NSCalendarType.Gregorian);
			calendar.FirstWeekDay = 2;
			NSDate date = NSDate.Now;
			NSDateComponents components = new NSDateComponents ();
			components.Year = -10;
			NSDate minDate = calendar.DateByAddingComponents (components, date, (NSCalendarOptions)0);
			components.Year = 10;
			NSDate maxDate = calendar.DateByAddingComponents (components, date, (NSCalendarOptions)0);

			this.CalendarView = new TKCalendar (this.View.Bounds);
			this.CalendarView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
			this.View.AddSubview (this.CalendarView);

			this.calendarDelegate = new CalendarDelegate(this);

			this.CalendarView.Delegate = calendarDelegate;
			this.CalendarView.ViewMode = TKCalendarViewMode.Year;
			this.CalendarView.Calendar = calendar;
			this.CalendarView.MinDate = minDate;
			this.CalendarView.MaxDate = maxDate;
			this.CalendarView.NavigateToDate (date, false);
		}
예제 #2
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            NSCalendar calendar = new NSCalendar(NSCalendarType.Gregorian);

            calendar.FirstWeekDay = 2;
            NSDate           date       = NSDate.Now;
            NSDateComponents components = new NSDateComponents();

            components.Year = -10;
            NSDate minDate = calendar.DateByAddingComponents(components, date, (NSCalendarOptions)0);

            components.Year = 10;
            NSDate maxDate = calendar.DateByAddingComponents(components, date, (NSCalendarOptions)0);

            this.CalendarView = new TKCalendar(this.View.Bounds);
            this.CalendarView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            this.View.AddSubview(this.CalendarView);

            this.CalendarView.Delegate = new CalendarDelegate(this);
            this.CalendarView.ViewMode = TKCalendarViewMode.Year;
            this.CalendarView.Calendar = calendar;
            this.CalendarView.MinDate  = minDate;
            this.CalendarView.MaxDate  = maxDate;
            this.CalendarView.NavigateToDate(date, false);
        }
예제 #3
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            this.tableViewDataSource = new TableViewDataSource(this);

            this.TableView = new UITableView(new RectangleF());
            this.TableView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin;
            this.TableView.RegisterClassForCellReuse(typeof(UITableViewCell), new NSString("cell"));
            this.TableView.DataSource = this.tableViewDataSource;
            this.View.AddSubview(this.TableView);

            NSCalendar calendar = new NSCalendar(NSCalendarType.Gregorian);

            calendar.FirstWeekDay = 2;

            NSDateComponents components = new NSDateComponents();

            components.Year = -10;
            NSDate minDate = calendar.DateByAddingComponents(components, NSDate.Now, (NSCalendarOptions)0);

            components.Year = 10;
            NSDate maxDate = calendar.DateByAddingComponents(components, NSDate.Now, (NSCalendarOptions)0);

            this.calendarDelegate   = new CalendarDelegate(this);
            this.calendarDataSource = new CalendarDataSource(this);

            this.CalendarView = new TKCalendar(new RectangleF());
            this.CalendarView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            this.CalendarView.Calendar         = calendar;
            this.CalendarView.Delegate         = calendarDelegate;
            this.CalendarView.DataSource       = calendarDataSource;
            // >> navigation-minmaxdate-cs
            this.CalendarView.MinDate = minDate;
            this.CalendarView.MaxDate = maxDate;
            // << navigation-minmaxdate-cs
            this.CalendarView.AllowPinchZoom = true;

            TKCalendarMonthPresenter presenter = (TKCalendarMonthPresenter)this.CalendarView.Presenter;

            presenter.Style.TitleCellHeight = 40;
            presenter.HeaderIsSticky        = true;

            if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad)
            {
                presenter.WeekNumbersHidden = true;
                // >> customizations-ipad-cs
                this.CalendarView.Theme = new TKCalendarIPadTheme();
                // << customizations-ipad-cs
                presenter.Update(true);
            }
            else
            {
                presenter.WeekNumbersHidden = false;
            }

            this.View.AddSubview(this.CalendarView);
        }
예제 #4
0
		List<WeatherModel> addPopulationData()
		{
			List<WeatherModel> array = new List<WeatherModel>();

			NSDate now = NSDate.Now;


			string[] imagesArray = new string[] { "Cloudy.png", "Humid.png", "Rainy.png", "Warm.png", "Windy.png", "Cloudy.png", "Humid.png" };
			for (int i = 0; i < 7; i++)
			{
				int daysToAdd = i;
				NSDateComponents components = new NSDateComponents();
				components.Day = daysToAdd;

				NSCalendar gregorian =  NSCalendar.CurrentCalendar;

				NSDate newDate2 = gregorian.DateByAddingComponents(components, now, NSCalendarOptions.None);
				NSDateFormatter dateFormatter = new NSDateFormatter();
				dateFormatter.DateFormat = "EEEE, MMMM dd";

				NSDateFormatter dateFormatter1 = new NSDateFormatter();
				dateFormatter1.DateFormat = "EEEE";
				array.Add(new WeatherModel((NSString)dateFormatter.StringFor(newDate2), (NSString)imagesArray[i], (NSString)new Random().Next(10, 40).ToString(), (NSString)dateFormatter1.StringFor(newDate2)));
			}

			return array;
		}
예제 #5
0
        static void Main(string[] args)
        {
            NSApplication.Init();

            NSDate           now            = NSDate.Now;
            DateTime         cNow           = DateTime.UtcNow;
            NSCalendar       cal            = NSCalendar.CurrentCalendar;
            NSDateComponents weekComponents = new NSDateComponents();

            List <LotteryEntry> entries = new List <LotteryEntry>();

            for (int i = 0; i < 10; i++)
            {
                weekComponents.Week = i;
                NSDate iWeeksFromNow = cal.DateByAddingComponents(weekComponents, now, NSCalendarOptions.None);

                DateTime cWeeksFromNow = cNow.AddDays(i * 7);

                LotteryEntry newEntry = new LotteryEntry(iWeeksFromNow, cWeeksFromNow);
                entries.Add(newEntry);
            }

            foreach (LotteryEntry entry in entries)
            {
                Debug.WriteLine("{0}", entry);
            }

            NSApplication.Main(args);
        }
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            commonHelper = new CommonHelper();
            this.NavigationItem.Title = "Last Worn Date";

            // create next button
            nextButton = new UIBarButtonItem("Other Details", UIBarButtonItemStyle.Plain, NextButtonClickAction);
            NavigationItem.SetRightBarButtonItem(nextButton, true);

            // create previous button
            prevButton = new UIBarButtonItem("ItemType", UIBarButtonItemStyle.Plain, PrevButtonClickAction);
            NavigationItem.SetLeftBarButtonItem(prevButton, true);


            var calendar    = new NSCalendar(NSCalendarType.Gregorian);
            var currentDate = NSDate.Now;
            var components  = new NSDateComponents();

            components.Year = -60;

            NSDate minDate = calendar.DateByAddingComponents(components, NSDate.Now, NSCalendarOptions.None);

            Console.WriteLine("ViewDidLoad, before AddScreenLayout wardrobeObj" + wardrobeObj.ItemType);



            AddScreenLayout();
        }
예제 #7
0
		public override void ViewDidLoad ()
		{
			base.ViewDidLoad ();

			this.tableViewDataSource = new TableViewDataSource (this);

			this.TableView = new UITableView (new RectangleF ());
			this.TableView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleTopMargin;
			this.TableView.RegisterClassForCellReuse (typeof(UITableViewCell), new NSString("cell"));
			this.TableView.DataSource = this.tableViewDataSource;
			this.View.AddSubview (this.TableView);

			NSCalendar calendar = new NSCalendar (NSCalendarType.Gregorian);
			calendar.FirstWeekDay = 2;

			NSDateComponents components = new NSDateComponents ();
			components.Year = -10;
			NSDate minDate = calendar.DateByAddingComponents (components, NSDate.Now, (NSCalendarOptions)0);
			components.Year = 10;
			NSDate maxDate = calendar.DateByAddingComponents (components, NSDate.Now, (NSCalendarOptions)0);

			this.calendarDelegate = new CalendarDelegate (this);
			this.calendarDataSource = new CalendarDataSource (this);

			this.CalendarView = new TKCalendar (new RectangleF());
			this.CalendarView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
			this.CalendarView.Calendar = calendar;
			this.CalendarView.Delegate = calendarDelegate;
			this.CalendarView.DataSource = calendarDataSource;
			this.CalendarView.MinDate = minDate;
			this.CalendarView.MaxDate = maxDate;
			this.CalendarView.AllowPinchZoom = true;

			TKCalendarMonthPresenter presenter = (TKCalendarMonthPresenter)this.CalendarView.Presenter;
			presenter.Style.TitleCellHeight = 40;
			presenter.HeaderIsSticky = true;

			if (UIDevice.CurrentDevice.UserInterfaceIdiom == UIUserInterfaceIdiom.Pad) {
				presenter.WeekNumbersHidden = true;
				this.CalendarView.Theme = new TKCalendarIPadTheme ();
				presenter.Update (true);
			} else {
				presenter.WeekNumbersHidden = false;
			}

			this.View.AddSubview (this.CalendarView);
		}
예제 #8
0
        public override void ViewDidLoad()
        {
            this.AddOption("Year", SelectYear);
            this.AddOption("Month", SelectMonth);
            this.AddOption("Month Names", SelectMonthNames);
            this.AddOption("Year Numbers", SelectYearNumbers);
            this.AddOption("Flow", SelectFlow);
            this.AddOption("Week view", SelectWeekView);

            base.ViewDidLoad();

            NSCalendar calendar = new NSCalendar(NSCalendarType.Gregorian);

            calendar.FirstWeekDay = 2;
            NSDate           date       = NSDate.Now;
            NSDateComponents components = new NSDateComponents();

            components.Year = -10;
            NSDate minDate = calendar.DateByAddingComponents(components, date, (NSCalendarOptions)0);

            components.Year = 10;
            NSDate maxDate = calendar.DateByAddingComponents(components, date, (NSCalendarOptions)0);

            this.CalendarView = new TKCalendar(this.View.Bounds);
            this.CalendarView.AutoresizingMask = UIViewAutoresizing.FlexibleWidth | UIViewAutoresizing.FlexibleHeight;
            this.View.AddSubview(this.CalendarView);

            this.calendarDelegate = new CalendarDelegate(this);

            this.CalendarView.Delegate = calendarDelegate;
            this.CalendarView.ViewMode = TKCalendarViewMode.Year;
            this.CalendarView.Calendar = calendar;
            this.CalendarView.MinDate  = minDate;
            this.CalendarView.MaxDate  = maxDate;
            // >> view-modes-pinchzoom-cs
            this.CalendarView.AllowPinchZoom = false;
            // << view-modes-pinchzoom-cs
            this.CalendarView.NavigateToDate(date, false);

            // >> view-modes-presenter-cs
            TKCalendarYearPresenter presenter = (TKCalendarYearPresenter)this.CalendarView.Presenter;

            presenter.Columns = 3;
            // << view-modes-presenter-cs
        }
예제 #9
0
        public NSDate DateWithOffset(int days, int hours)
        {
            NSCalendar       calendar   = NSCalendar.CurrentCalendar;
            NSDateComponents components = new NSDateComponents();

            components.Day  = days;
            components.Hour = hours;
            return(calendar.DateByAddingComponents(components, NSDate.Now, (NSCalendarOptions)0));
        }
예제 #10
0
        public void DateByAddingComponentsTest()
        {
            var    cal   = new NSCalendar(NSCalendarType.Gregorian);
            var    now   = (NSDate)DateTime.Now;
            var    comps = new NSDateComponents();
            NSDate date;

            comps.Day      = 2;
            comps.TimeZone = NSTimeZone.FromAbbreviation("UTC");
            cal.TimeZone   = comps.TimeZone;

#if !NET
            date = cal.DateByAddingComponents(comps, now, NSDateComponentsWrappingBehavior.None);
            Assert.AreEqual(now.SecondsSinceReferenceDate + 3600 * 24 * 2, date.SecondsSinceReferenceDate, "a");
#endif

            date = cal.DateByAddingComponents(comps, now, NSCalendarOptions.None);
            Assert.AreEqual(now.SecondsSinceReferenceDate + 3600 * 24 * 2, date.SecondsSinceReferenceDate, "b");
        }
예제 #11
0
        void AddItem(NSMutableArray array, string name, float value, string group, int day, UIImage image)
        {
            NSCalendar       calendar   = NSCalendar.CurrentCalendar;
            NSDateComponents components = new NSDateComponents();

            components.Day = day;
            NSDate date = calendar.DateByAddingComponents(components, NSDate.Now, NSCalendarOptions.None);
            DSItem item = new DSItem()
            {
                Name  = name,
                Value = value,
                Group = group,
                Date  = date,
                Image = image
            };

            array.Add(item);
        }
예제 #12
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            datePickerMode.SelectedSegment = 0;
            datePickerView.Mode            = UIDatePickerMode.Time;
            //datePickerView.TimeZone = NSTimeZone.FromName("America/New_York");
            //datePickerView.Locale = NSLocale.FromLocaleIdentifier("en_GB");

            var calendar    = new NSCalendar(NSCalendarType.Gregorian);
            var currentDate = NSDate.Now;
            var components  = new NSDateComponents();

            components.Year = -60;

            NSDate minDate = calendar.DateByAddingComponents(components, NSDate.Now, NSCalendarOptions.None);

            //Uncomment to set min and max date

            //datePickerView.MinimumDate = minDate;
            //datePickerView.MaximumDate = (NSDate)DateTime.Today.AddYears(-7);
        }
예제 #13
0
        public override void ViewDidLoad()
        {
            base.ViewDidLoad();

            //Starting off by initilizing all of the components of the view.

            var stackView = new UIStackView
            {
                Axis         = UILayoutConstraintAxis.Vertical,
                Alignment    = UIStackViewAlignment.Fill,
                Distribution = UIStackViewDistribution.EqualSpacing,
                Spacing      = 25,
                TranslatesAutoresizingMaskIntoConstraints = false
            };

            var scrollView = new UIScrollView(new CGRect(0, 0, View.Frame.Width, View.Frame.Height));

            var NameField = new UITextField
            {
                Frame       = new CGRect(25, 20, 35, 15),
                Placeholder = "Event Name"
            };
            var AddressField = new UITextField
            {
                Frame       = new CGRect(25, 30, 35, 15),
                Placeholder = "Address"
            };
            var CityFiled = new UITextField
            {
                Frame       = new CGRect(25, 40, 35, 15),
                Placeholder = "City"
            };
            var StateField = new UITextField
            {
                Frame       = new CGRect(25, 30, 35, 15),
                Placeholder = "State"
            };
            var CountryField = new UITextField
            {
                Frame       = new CGRect(25, 30, 35, 15),
                Placeholder = "Country"
            };
            var ZipField = new UITextField
            {
                Frame       = new CGRect(25, 50, 35, 15),
                Placeholder = "ZipCode"
            };
            var DescField = new UITextField
            {
                Frame       = new CGRect(25, 50, 35, 15),
                Placeholder = "Event Description"
            };
            var SubmitButton = new UIButton(UIButtonType.System)
            {
                Frame = new CGRect(25, 90, 300, 30)
            };
            var GetImage = new UIButton(UIButtonType.System)
            {
                Frame = new CGRect(25, 60, 300, 30)
            };
            var StateLabel = new UILabel()
            {
                Text          = "Press the button to choose between Public or Private.",
                TextAlignment = UITextAlignment.Center
            };
            var isPublicButton = new UIButton(UIButtonType.System)
            {
                Frame = new CGRect(25, 90, 300, 30)
            };


            UIDatePicker DatePicker = new UIDatePicker(new CGRect(
                                                           UIScreen.MainScreen.Bounds.X - UIScreen.MainScreen.Bounds.Width,
                                                           UIScreen.MainScreen.Bounds.Height - 230,
                                                           UIScreen.MainScreen.Bounds.Width,
                                                           180));
            var calendar = new NSCalendar(NSCalendarType.Gregorian);

            calendar.TimeZone = NSTimeZone.LocalTimeZone;
            var currentDate = NSDate.Now;
            var components  = new NSDateComponents();

            components.Year = -60;
            NSDate minDate = calendar.DateByAddingComponents(components, NSDate.Now, NSCalendarOptions.None);

            DatePicker.MinimumDate = currentDate;
            DatePicker.Mode        = UIDatePickerMode.DateAndTime;

            SubmitButton.SetTitle("Submit Event", UIControlState.Normal);
            GetImage.SetTitle("Pick An Image", UIControlState.Normal);
            isPublicButton.SetTitle("Private Event", UIControlState.Normal);


            //Start putting the components together to build the view.

            stackView.AddArrangedSubview(NameField);
            stackView.AddArrangedSubview(AddressField);
            stackView.AddArrangedSubview(CityFiled);
            stackView.AddArrangedSubview(StateField);
            stackView.AddArrangedSubview(CountryField);
            stackView.AddArrangedSubview(ZipField);
            stackView.AddArrangedSubview(DescField);
            stackView.AddArrangedSubview(DatePicker);
            stackView.AddArrangedSubview(StateLabel);
            stackView.AddArrangedSubview(isPublicButton);
            stackView.AddArrangedSubview(GetImage);
            stackView.AddArrangedSubview(SubmitButton);

            scrollView.AddSubview(stackView);

            View.Add(scrollView);

            //Finializing the layout.

            scrollView.ContentSize = stackView.Frame.Size;
            scrollView.AddConstraint(stackView.TopAnchor.ConstraintEqualTo(scrollView.TopAnchor));
            scrollView.AddConstraint(stackView.BottomAnchor.ConstraintEqualTo(scrollView.BottomAnchor));
            scrollView.AddConstraint(stackView.LeftAnchor.ConstraintEqualTo(scrollView.LeftAnchor));
            scrollView.AddConstraint(stackView.RightAnchor.ConstraintEqualTo(scrollView.RightAnchor));

            View.AddConstraint(scrollView.TopAnchor.ConstraintEqualTo(View.TopAnchor));
            View.AddConstraint(scrollView.BottomAnchor.ConstraintEqualTo(View.BottomAnchor));
            View.AddConstraint(scrollView.LeftAnchor.ConstraintEqualTo(View.LeftAnchor));
            View.AddConstraint(scrollView.RightAnchor.ConstraintEqualTo(View.RightAnchor));
            View.BackgroundColor = UIColor.White;
            var g = new UITapGestureRecognizer(() => View.EndEditing(true));

            View.AddGestureRecognizer(g);


            //Button function #1: submitting the event and presenting the submission to the user.
            SubmitButton.TouchUpInside += async(object sender, EventArgs e) =>
            {
                //Populate the Event model.
                userEvent.Address   = AddressField.Text;
                userEvent.EventName = NameField.Text;
                userEvent.City      = CityFiled.Text;
                userEvent.State     = StateField.Text;
                userEvent.Country   = CountryField.Text;
                userEvent.ZipCode   = int.Parse(ZipField.Text);
                DateTime.SpecifyKind((DateTime)DatePicker.Date, DateTimeKind.Utc).ToLocalTime();
                userEvent.DateOfEvent = (DateTime)DatePicker.Date;
                userEvent.isPublic    = isPublic;
                var    geoCoder     = new CLGeocoder();
                var    location     = new CLLocation();
                string worldAddress = userEvent.Address + ", "
                                      + userEvent.City + ", "
                                      + userEvent.State + ", "
                                      + userEvent.Country + ", "
                                      + userEvent.ZipCode.ToString();
                var placemarks = geoCoder.GeocodeAddressAsync(worldAddress);
                await placemarks.ContinueWith((addresses) =>
                {
                    foreach (var address in addresses.Result)
                    {
                        location = address.Location;
                    }
                });

                userEvent.Lat         = location.Coordinate.Latitude;
                userEvent.Long        = location.Coordinate.Longitude;
                userEvent.Description = DescField.Text;

                EventService ES = new EventService(_client);
                if (userImage != null)
                {
                    Event EventLocation = await ES.CreateNewEvent(userEvent, userImage);

                    var ShowEvent = new SubmittedEvent(EventLocation, _client, _locationmanager);
                    this.NavigationController.PopViewController(true);
                    this.NavigationController.PushViewController(ShowEvent, true);
                }
                else
                {
                    Event EventLocation = await ES.CreateNewEvent(userEvent);

                    var ShowEvent = new SubmittedEvent(EventLocation, _client, _locationmanager);
                    this.NavigationController.PopViewController(true);
                    this.NavigationController.PushViewController(ShowEvent, true);
                }
            };

            //Button function #2: opening Image Picker
            GetImage.TouchUpInside += (object sender, EventArgs e) =>
            {
                ShowSelectPicPopup();
            };

            //Button function #3: Public/Private toggle function
            isPublicButton.TouchUpInside += (object sender, EventArgs e) =>
            {
                if (isPublic == false)
                {
                    isPublic = true;
                    isPublicButton.SetTitle("Public Event", UIControlState.Normal);
                }
                else
                {
                    isPublic = false;
                    isPublicButton.SetTitle("Private Event", UIControlState.Normal);
                }
            };
        }
예제 #14
0
		void AddEarthquakesToList (List<Earthquake> earthquakes)
		{
			var entity = NSEntityDescription.EntityForName ("Earthquake", managedObjectContext);
			var fetchRequest = new NSFetchRequest ();
			fetchRequest.Entity = entity;

			var date = (NSPropertyDescription)entity.PropertiesByName.ValueForKey (new NSString ("date"));
			var location = (NSPropertyDescription)entity.PropertiesByName.ValueForKey (new NSString ("location"));

			fetchRequest.PropertiesToFetch = new NSPropertyDescription[] { date, location };
			fetchRequest.ResultType = NSFetchRequestResultType.DictionaryResultType;

			NSError error;

			foreach (var earthquake in earthquakes) {
				var arguments = new NSObject[] { earthquake.Location, earthquake.Date };
				fetchRequest.Predicate = NSPredicate.FromFormat ("location = %@ AND date = %@", arguments);
				var fetchedItems = NSArray.FromNSObjects (managedObjectContext.ExecuteFetchRequest (fetchRequest, out error));

				if (fetchedItems.Count == 0) {

					if (string.IsNullOrEmpty (entity.Description))
						continue;

					var managedEarthquake = new ManagedEarthquake (entity, managedObjectContext) {
						Magnitude = earthquake.Magnitude,
						Location = earthquake.Location,
						Date = earthquake.Date,
						USGSWebLink = earthquake.USGSWebLink,
						Latitude = earthquake.Latitude,
						Longitude = earthquake.Longitude
					};

					managedObjectContext.InsertObject (managedEarthquake);
				}

				var gregorian = new NSCalendar (NSCalendarType.Gregorian);
				var offsetComponents = new NSDateComponents ();
				offsetComponents.Day = -14;// 14 days back from today
				NSDate twoWeeksAgo = gregorian.DateByAddingComponents (offsetComponents, NSDate.Now, NSCalendarOptions.None);

				// use the same fetchrequest instance but switch back to NSManagedObjectResultType
				fetchRequest.ResultType = NSFetchRequestResultType.ManagedObject;
				fetchRequest.Predicate = NSPredicate.FromFormat ("date < %@", new NSObject[] { twoWeeksAgo });

				var olderEarthquakes = NSArray.FromObjects (managedObjectContext.ExecuteFetchRequest (fetchRequest, out error));

				for (nuint i = 0; i < olderEarthquakes.Count; i++)
					managedObjectContext.DeleteObject (olderEarthquakes.GetItem<ManagedEarthquake> (i));

				if (managedObjectContext.HasChanges) {
					if (!managedObjectContext.Save (out error))
						Console.WriteLine (string.Format ("Unresolved error {0}", error.LocalizedDescription));
				}
			}
		}
예제 #15
0
        private void AddEarthquakesToList(List <Earthquake> earthquakes)
        {
            var entity       = NSEntityDescription.EntityForName("Earthquake", managedObjectContext);
            var fetchRequest = new NSFetchRequest();

            fetchRequest.Entity = entity;

            var date     = (NSPropertyDescription)entity.PropertiesByName.ValueForKey(new NSString("date"));
            var location = (NSPropertyDescription)entity.PropertiesByName.ValueForKey(new NSString("location"));

            fetchRequest.PropertiesToFetch = new NSPropertyDescription[] { date, location };
            fetchRequest.ResultType        = NSFetchRequestResultType.DictionaryResultType;

            NSError error;

            foreach (var earthquake in earthquakes)
            {
                var arguments = new NSObject[] { earthquake.Location, earthquake.Date };
                fetchRequest.Predicate = NSPredicate.FromFormat(@"location = %@ AND date = %@", arguments);
                var fetchedItems = NSArray.FromNSObjects(managedObjectContext.ExecuteFetchRequest(fetchRequest, out error));

                if (fetchedItems.Count == 0)
                {
                    if (string.IsNullOrEmpty(entity.Description))
                    {
                        continue;
                    }

                    var managedEarthquake = new ManagedEarthquake(entity, managedObjectContext)
                    {
                        Magnitude   = earthquake.Magnitude,
                        Location    = earthquake.Location,
                        Date        = earthquake.Date,
                        USGSWebLink = earthquake.USGSWebLink,
                        Latitude    = earthquake.Latitude,
                        Longitude   = earthquake.Longitude
                    };

                    managedObjectContext.InsertObject(managedEarthquake);
                }

                var gregorian        = new NSCalendar(NSCalendarType.Gregorian);
                var offsetComponents = new NSDateComponents();
                offsetComponents.Day = -14;                // 14 days back from today
                NSDate twoWeeksAgo = gregorian.DateByAddingComponents(offsetComponents, NSDate.Now, NSCalendarOptions.None);

                // use the same fetchrequest instance but switch back to NSManagedObjectResultType
                fetchRequest.ResultType = NSFetchRequestResultType.ManagedObject;
                fetchRequest.Predicate  = NSPredicate.FromFormat(@"date < %@", new NSObject[] { twoWeeksAgo });

                var olderEarthquakes = NSArray.FromObjects(managedObjectContext.ExecuteFetchRequest(fetchRequest, out error));

                for (int i = 0; i < olderEarthquakes.Count; i++)
                {
                    managedObjectContext.DeleteObject(olderEarthquakes.GetItem <ManagedEarthquake> (i));
                }

                if (managedObjectContext.HasChanges)
                {
                    if (!managedObjectContext.Save(out error))
                    {
                        Console.WriteLine(string.Format("Unresolved error {0}", error.LocalizedDescription));
                    }
                }
            }
        }