Get events from a specific calendar in IOS - objective-c

I am trying to fetch events from a specific calendar only. On my iPhone I added a calendar "CalendarTest". What I want to do is in my app only fetch the events from that Calendar. I am doing the following.
self.defaultCalendar = [eventStore calendarWithIdentifier:#"CalendarTest"];
NSArray *calendarArray = [NSArray arrayWithObject:defaultCalendar];
// asynchronous callback on the main thread
[events removeAllObjects];
NSLog(#"Fetching events from EventKit between %# and %# on a GCD-managed background thread...", fromDate, toDate);
dispatch_async(eventStoreQueue, ^{
NSDate *fetchProfilerStart = [NSDate date];
NSPredicate *predicate = [eventStore predicateForEventsWithStartDate:fromDate endDate:toDate calendars:calendarArray];
NSArray *matchedEvents = [eventStore eventsMatchingPredicate:predicate];
dispatch_async(dispatch_get_main_queue(), ^{
NSLog(#"Fetched %d events in %f seconds", [matchedEvents count], -1.f * [fetchProfilerStart timeIntervalSinceNow]);
[events addObjectsFromArray:matchedEvents];
[delegate loadedDataSource:self];
});
});
But when I build and run I get the following error it crashes with the following error.
2012-11-20 11:45:35.445 CalendarApp[2685:1d03] *** Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '*** -[__NSPlaceholderArray initWithObjects:count:]: attempt to insert nil object from objects[0]'
Anybody has an idea? Kind regards!

I think you should add self.defaultCalendar to your calendarArray. That might do the trick.

Related

Error when reading workout route data from health kit in Objective C

In health kit when I try to collect route data from the workout sample I get the error:
Domain=NSCocoaErrorDomain Code=4099 "The connection to service on pid 0 named com.apple.healthd.server was interrupted, but the message was sent over an additional proxy and therefore this proxy has become invalid." UserInfo={NSDebugDescription=The connection to service on pid 0 named com.apple.healthd.server was interrupted, but the message was sent over an additional proxy and therefore this proxy has become invalid.
I have already obtained workout and workout route permissions and I have imported core location and obtained “when in use” location permission. I am using a real iPhone 8 for testing not the simulator.
My code is below. Any help would be appreciated.
NSCalendar *cal = [NSCalendar currentCalendar];
NSDate *someDate = [cal dateByAddingUnit:NSCalendarUnitDay value:(-3) toDate:[NSDate date]
options:0];
NSDate *startOfDay = [[NSCalendar calendarWithIdentifier:NSCalendarIdentifierGregorian]
startOfDayForDate:someDate];
NSPredicate *predicate = [HKQuery predicateForSamplesWithStartDate:startOfDay endDate:
[NSDate date] options:HKQueryOptionStrictStartDate];
HKAnchoredObjectQuery *query = [[HKAnchoredObjectQuery alloc] initWithType:[HKWorkoutType
workoutType] predicate:predicate anchor:nil limit:HKObjectQueryNoLimit
resultsHandler:^(HKAnchoredObjectQuery * _Nonnull query, NSArray * _Nullable samples,
NSArray * _Nullable deletedObjects, HKQueryAnchor* anchor, NSError * _Nullable error) {
if (error != nil) {
NSLog(#" %#",error);
} else {
HKWorkoutRoute * myRoute=samples[0];
HKWorkoutRouteQuery * queryroute= [[HKWorkoutRouteQuery alloc]
initWithRoute:myRoute
dataHandler:^(HKWorkoutRouteQuery * _Nonnull
query, NSArray<CLLocation *> * _Nullable
routeData, BOOL done, NSError *
_Nullable error) {
NSLog(#" GETTING ROUTE 1 ");
if (error != nil) {
NSLog(#" %#“,error);
} else {
}
if(done){
NSLog(#"route data %#",routeData);
}else{
}
}];
[self.healthStore executeQuery:queryroute];
}}];//end anchor
[self.healthStore executeQuery:query];

iOS 8 : App crashes while trying to remove single event from device calendar

I Have used EKSpanThisEvent so when I try to remove single event from device calendar it crashes, Instead of that if I use EKSpanFutureEvents it does not get crash but it will remove all future events with same eventIdentifier even though we try to remove single event from device calendar
Crash detail is as Follow
Assertion failure in -[EKEvent _deleteThisOccurrence]
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: 'I screwed up somewhere in date calculation'
I tried all solutions from all sources but unfortunately none was useful, Any Help will be Highly Appreciated
CODE
if([identifier length] > 0)
{
__block EKEventStore* store = [[EKEventStore alloc] init];
[store requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (!granted) return;
NSDate *eventdate = [commonUnit getSystemTimeZoneDateFromDate:strdate fromFormate:#"yyyy-MM-dd"];
NSPredicate *predicate = [store predicateForEventsWithStartDate:eventdate
endDate:[eventdate dateByAddingTimeInterval:86400]
calendars:nil];
NSMutableArray *events = [NSMutableArray arrayWithArray:[store eventsMatchingPredicate:predicate]];
NSPredicate *predicateidentifier = [NSPredicate predicateWithFormat:[NSString stringWithFormat:#"eventIdentifier = '%#'",identifier]];
[events filterUsingPredicate:predicateidentifier];
if (events.count > 0) {
NSError* error = nil;
[store removeEvent:events[0] span:status?EKSpanFutureEvents:EKSpanThisEvent commit:YES error:&error];
if(error == nil)
{
callbackBlock(TRUE);
}
else
{
callbackBlock(FALSE);
}
}
}];
}

UIRefreshControl - Terminating app due to uncaught exception

I implemented UIRefreshControl on a Table View inside a UITableViewController. Today my friend (first tester) was playing with the app and he was able to make crash by pulling to refresh and while it's refreshing, pulling on it again very quickly a couple of times. I know it's not a common thing to do but I can recreate it very easily. I'm guessing there's something wrong with the way I'm implementing the refresh control since I tried to recreate it with the Gmail app and it didn't crash.
This is the error I get:
[1008:907] * Terminating app due to uncaught exception 'NSInvalidArgumentException', reason: '* -[__NSCFConstantString stringByAppendingString:]: nil argument'
* First throw call stack:
(0x343f32a3 0x3c08d97f 0x343f31c5 0x34c5c5e1 0x496b5 0x3624654d 0x3622b313 0x362427cf 0x361fe803 0x35fa8d8b 0x35fa8929 0x35fa985d 0x35fa9243 0x35fa9051 0x35fa8eb1 0x343c86cd 0x343c69c1 0x343c6d17 0x34339ebd 0x34339d49 0x37efb2eb 0x3624f301 0x46da5 0x3c4c4b20)
libc++abi.dylib: terminate called throwing an exception
(lldb)
Under ViewDidLoad
// pull to refresh
UIRefreshControl *refreshControl = [[UIRefreshControl alloc] init];
[refreshControl addTarget:self action:#selector(updateTableView:) forControlEvents:UIControlEventValueChanged];
[self setRefreshControl:refreshControl];
And this is the updateTableView method:
- (void)updateTableView:(id)sender {
NSDateFormatter *formatter = [[NSDateFormatter alloc] init];
[formatter setDateFormat:#"MMM d, h:mm:ss a"];
NSString *lastUpdated = [NSString stringWithFormat:#"Last updated on %#", [formatter stringFromDate:[NSDate date]]];
self.refreshControl.attributedTitle = [[NSAttributedString alloc] initWithString:lastUpdated];
if(topOptions.selectedSegmentIndex == 0) {
//fetch the feed
_feed = [[FetchData alloc] initFromURLWithString:#"some json file" completion:^(JSONModel *model, JSONModelError *err) {
[self.tableView reloadData];
[(UIRefreshControl *)sender endRefreshing];
}];
} else if (topOptions.selectedSegmentIndex == 1) {
//fetch the feed
_feed = [[FetchData alloc] initFromURLWithString:#"another json file" completion:^(JSONModel *model, JSONModelError *err) {
[self.tableView reloadData];
[(UIRefreshControl *)sender endRefreshing];
}];
}
}
I'm guessing (from the nil argument) that by doing the refresh request many times it reaches a point that it can't find a value? I'm kind of new at this so any idea is really appreciated.
If you need any other part of the code let me know.

Error in NSMutableArray

I am very new to ios development, I am trying to add some values from NSMutableDictionary to NSMutableArray, when I run the code I get this error
2012-05-29 14:09:34.913 iShop[7464:f803] -[__NSCFArray objectForKey:]:
unrecognized selector sent to instance 0x6e423d0 2012-05-29
14:09:34.915 iShop[7464:f803] * Terminating app due to uncaught
exception 'NSInvalidArgumentException', reason: '-[__NSCFArray
objectForKey:]: unrecognized selector sent to instance 0x6e423d0'
* First throw call stack: (0x13cb022 0x155ccd6 0x13cccbd 0x1331ed0 0x1331cb2 0x2bb7 0x13cce42 0x93b9df 0x139f94f 0x1302b43 0x1302424
0x1301d84 0x1301c9b 0x12b47d8 0x12b488a 0x15626 0x28bd 0x2825)
terminate called throwing an exception(lldb)
below is my code:
-(void) getData:(NSData *) response {
NSError *error;
NSMutableDictionary *json = [NSJSONSerialization JSONObjectWithData:response options:kNilOptions error:&error];
//NSLog(#"%#", json);
jsonArray = [[NSMutableArray alloc] init];
jsonArray = [json objectForKey:#"Name"];
NSLog(#"%#", jsonArray);
}
- (void)viewDidLoad {
[super viewDidLoad];
jsonURL = [NSURL URLWithString:#"http://localhost:8888/read_product_list.php"];
dispatch_async(BgQueue, ^{
NSData* data = [NSData dataWithContentsOfURL:jsonURL];
[self performSelectorOnMainThread:#selector(getData:)
withObject:data waitUntilDone:YES];
});
}
JSONObjectWithData return an object of type id. depending on the structure of your received json data.
The data recieved is eiher NSDictionary or NSArray. In your case I am guessing the top level object is of type NSArray which does not respond to objectForKey

-[CFString hash]: message sent to deallocated instance

I'm trying to fetch EKEvents from the Event Store to populate a UITableView and display a month list view.
Basically it works and I'm doing it like this:
- (void) reloadEvents
{
for ( NSString *entry in self.calendarA )
{
NSMutableArray *tempArray = [[[NSMutableArray alloc] init] autorelease];
[tempArray addObjectsFromArray:[appDelegate.eventStore eventsMatchingPredicate:[appDelegate.eventStore predicateForEventsWithStartDate:[NSDate fromString:entry] endDate:[[NSDate fromString:entry] midnight] calendars:nil]]];
[tempArray addObjectsFromArray:[self initializeItems:[NSDate fromString:entry] withEndDate:[[NSDate fromString:entry] midnight]]];
[tempArray sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:#"startDate" ascending:YES] autorelease]]];
[[self.calendarD objectForKey:entry] addObjectsFromArray:tempArray];
}
dispatch_async(dispatch_get_main_queue(), ^(void)
{
[self redrawTableCells];
});
}
reloadEvents is called from within a
dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^(void)
{
[self reloadEvents];
});
as fetching events happens synchronously and it locks the UI for that time, I'm using GCD. The NSDate parts are my own categories on NSDate.
Now, when my view controller loads, events are fetched from the Event Store and displayed correctly. The view controller also listens for EKEventStoreChangedNotification and that's where my app crashes. When I change an event outside my app it receives a notification and tries to reload the event data, but then...
*** -[CFString length]: message sent to deallocated instance 0x666f530
EDIT
I've changed reloadEvents to the following:
- (void) reloadEvents
{
NSArray *daysArray = [[self.calendarD allKeys] sortedArrayUsingSelector:#selector(compare:)];
for ( NSString *entry in daysArray )
{
NSMutableArray *tempArray = [[NSMutableArray alloc] init];
[tempArray addObjectsFromArray:[appDelegate.eventStore eventsMatchingPredicate:[appDelegate.eventStore predicateForEventsWithStartDate:[NSDate fromString:entry] endDate:[[NSDate fromString:entry] midnight] calendars:nil]]];
[tempArray addObjectsFromArray:[self initializeItems:[NSDate fromString:entry] withEndDate:[[NSDate fromString:entry] midnight]]];
[tempArray sortUsingDescriptors:[NSArray arrayWithObject:[[[NSSortDescriptor alloc] initWithKey:#"startDate" ascending:YES] autorelease]]];
[[self.calendarD objectForKey:entry] addObjectsFromArray:tempArray];
[tempArray release];
}
dispatch_async(dispatch_get_main_queue(), ^(void)
{
[self redrawTableCells];
});
}
and with this, the app doesn't crash anymore.
Seems like something changed calendarA and therefore the entry was already deallocated (which, after having found the cause of the problem, is absolutely logical).