I would like to know how I can create a notification when the altitude is increasing and a notification when the altitude decreasing.
I already tried this code but I've no idea what to do next.
- (CMAltimeter *)altimeter {
if (!_altimeter) {
_altimeter = [[CMAltimeter alloc]init];
}
if ([CMAltimeter isRelativeAltitudeAvailable]) {
CMAltimeter* altimeter = [[CMAltimeter alloc] init];
NSOperationQueue* queue = [[NSOperationQueue alloc] init];
[altimeter startRelativeAltitudeUpdatesToQueue:queue withHandler:^(CMAltitudeData* altitudeData, NSError* error) {
}];
}
return _altimeter;
}
You pull out the data each time there's an update:
[altimeter startRelativeAltitudeUpdatesToQueue:queue
withHandler:^(CMAltitudeData* altitudeData, NSError* error)
{
// Put your data-handling code here -- for example,
// if your display has an element userRelAltitude
// that displays text:
float relAltitude;
relAltitude = altitudeData.relativeAltitude.floatValue;
self.userRelAltitude.text = [NSString stringWithFormat:#"%.0f m", relAltitude];
}];
Then you can compare each value to the previous one to see if it's increasing or decreasing and display an appropriate notification.
Related
I have a curious problem where my boolean variable is changing before I can assign it to a variable to be read in my react native code for Spotify SDK.
I have pinpointed the EXACT location as to where it changes and I am currently trying to figure out why:
I have a boolean called isLoggedIn that is set equal to 1 if a successful login occurs. This variable then sets loggedIn to a boolean value which is sent to my React Native code:
else
{
// login successful
NSLog(#"What is the value of isLoggedIn %#", [self isLoggedIn]);
////THIS shows that isLoggedIn still equal to 1.
[self initializePlayerIfNeeded:[RNSpotifyCompletion onComplete:^(id unused, RNSpotifyError* unusedError) {
NSLog(#"What is the value of isLoggedIn right after %#", [self isLoggedIn]);
/////NOW the isLoggedIn variable is now equal to 0.
// do UI logic on main thread
dispatch_async(dispatch_get_main_queue(), ^{
[authController.presentingViewController dismissViewControllerAnimated:YES completion:^{
_loggingIn = NO;
NSLog(#"What is the value of isLoggedIn %#", [self isLoggedIn]);
NSNumber* loggedIn = [self isLoggedIn]; /////this is the line we need to be == 1
resolve(loggedIn);
if(loggedIn.boolValue)
{
[self sendEvent:#"login" args:#[]];
}
}];
});
}]];
}
So obviously I assume that it is due to this line right?:
[self initializePlayerIfNeeded:[RNSpotifyCompletion onComplete:^(id unused, RNSpotifyError* unusedError)
Which is running this method: initializePlayerIfNeeded but when I read the value of the isLoggedIn variable at the end of this method it still shows a boolean value of 1 (look at last line):
-(void)initializePlayerIfNeeded:(RNSpotifyCompletion*)completion
{
if(![self hasPlayerScope])
{
[completion resolve:nil];
return;
}
// ensure only one thread is invoking the initialization at a time
BOOL initializedPlayer = NO;
NSError* error = nil;
BOOL allowCaching = (_cacheSize.unsignedIntegerValue > 0);
#synchronized(_player)
{
// check if player is already initialized
if(_player.initialized)
{
initializedPlayer = YES;
}
else
{
initializedPlayer = [_player startWithClientId:_auth.clientID audioController:nil allowCaching:allowCaching error:&error];
}
}
// handle initialization failure
if(!initializedPlayer)
{
[completion reject:[RNSpotifyError errorWithNSError:error]];
return;
}
// setup player
_player.delegate = self;
_player.playbackDelegate = self;
if(allowCaching)
{
_player.diskCache = [[SPTDiskCache alloc] initWithCapacity:_cacheSize.unsignedIntegerValue];
}
// attempt to log in the player
[self loginPlayer:completion];
NSLog(#"What is the value of isLoggedIn %#", [self isLoggedIn]);
////THIS shows that isLoggedIn still equal to 1.
}
So that method finishes up with the value still equal to 1, but why after that method returns does the next line show that isLoggedIn equal to 0? I am extremely new to objC so every bit of knowledge is helpful for me. I am using this React Native Spotify library from github: https://github.com/lufinkey/react-native-spotify
You can find the exact file I'm working with here: https://github.com/lufinkey/react-native-spotify/blob/master/ios/RNSpotify.m
What else would you need to help solve this?
EDIT: here's the method that changes the isLoggedIn:
RCT_EXPORT_BLOCKING_SYNCHRONOUS_METHOD(isLoggedIn)
{
if(!_initialized)
{
return #NO;
}
else if(_auth.session == nil)
{
return #NO;
}
return #YES;
}
I create UIAlertView in my function, the problem is it shows a lot of time when the function runs, how can I create an if statement to show only one time like if UIAlertView shows not show any more.
- (void)showAlert {
_myAlertView = nil;
_myAlertView = [[UIAlertView alloc] initWithTitle:NSLocalizedString(#"Call_On_Hold",nil)
message:NSLocalizedString(#"Please_Wait",nil)
delegate:self
cancelButtonTitle:NSLocalizedString(#"Close_call",nil)
otherButtonTitles:nil, nil];
_myAlertView.tag = myAlertViewsTag;
[_myAlertView show];
}
Here is the function that my UIAlertView appear continuously instead of one time.
- (void) trafficTimerRun:(NSTimer*)theTimer
{
++ trafficTimerTicks;
pjmedia_rtcp_stat stat;
if (!get_stream_info([call_id intValue], &stat)) {
return;
}
LogDebug(TAG_SIP, #"Got %d bytes on stream 0 (previous: %d)", stat.rx.bytes, prev_bytes);
if (stat.rx.bytes == prev_bytes) {
if (trafficTimerTicks >= 10) {
// Steve-note: Here we need to show a pop-up message when the call in on hold when the trafficTimerTicks run.
[self showAlert];
LogError(TAG_SIP, #"No traffic received, hanging up");
// [theTimer invalidate];
// broken = YES; Steve note: The call shouldnt broke.
// [self hangup]; Steve note: The call shouldnt hangup.
}
}
}
Use a boolean:
bool alertIsShowing = false;
and in your updating method put something like this:
if (trafficTicks > 10){
if (!alertIsShowing){
alertIsShowing = true;
[self showAlert];
}
}
Then when your alert is dismissed, reset your boolean:
alertIsShowing = false;
I am developing calendar app. I am trying to save EKEvent using assigned EKCalender. But when I try to run following code it gives me error. Please help
-(BOOL)createEventWithTitle:(NSString *)paramTitle startDate:(NSDate *)paramStartDate endDate:(NSDate *)paramEndDate inCalendar:(EKCalendar *)paramCalendar inEventStore:(EKEventStore *)paramStore notes:(NSString *)paramNotes
{
BOOL result = NO;
//paramCalendar = [self.eventStoreiReportShifts defaultCalendarForNewEvents];
if (self.eventsAccessGranted) {
NSArray *caledars = [self.eventStore calendarsForEntityType:EKEntityTypeEvent];
self.selectedCalendarEventKitIdentifier = [[NSUserDefaults standardUserDefaults] objectForKey:#"eventkit_cal_identifiers_string"];
for(EKCalendar *aCal in caledars){
if([aCal.calendarIdentifier isEqualToString:self.selectedCalendarEventKitIdentifier]){
paramCalendar = [self.eventStore calendarWithIdentifier:[[NSUserDefaults standardUserDefaults] objectForKey:#"eventkit_cal_identifiers_string"]];
}
}
for (EKSource *source in self.eventStore.sources) {
if (source.sourceType == EKSourceTypeCalDAV) {
paramCalendar.source = source;
break;
} else if(source.sourceType == EKSourceTypeLocal){
paramCalendar.source = source;
break;
}
}
}else{
return NO;
}
/* If a calendar does not allow modification of its contents
then we can not insert an event into it */
if (paramCalendar.allowsContentModifications == NO) {
NSLog (# "\n\n The selected calendar does not allow modifications.");
return NO;
}
/* Create an event */
EKEvent * event = [EKEvent eventWithEventStore:paramStore];
event.calendar = paramCalendar;
/* Set the properties of the event such as its title,
start date / time, end date / time, etc. */
event.title = paramTitle;
event.notes = paramNotes;
event.startDate = paramStartDate;
event.endDate = paramEndDate;
/* Finally, save the event into the calendar */
NSError * saveError = nil;
result = [paramStore saveEvent:event
span:EKSpanThisEvent
error:&saveError];
if (result == NO) {
NSLog (# "\n\n An error occurred = %#", saveError);
}
return result;
}
above code gives following error
CalendarCalculations[1668:45103]
Error getting shared calendar invitations for entity types 3 from
daemon: Error Domain=EKCADErrorDomain Code=1013
"The operation couldn’t be completed. (EKCADErrorDomain error 1013.)"
how can I get rid of it please?
I had the same problem in my app. I noticed the error occurs when calendarWithIdentifier method is called.
EKCalendar *selectedCalendar = [self.eventStore calendarWithIdentifier:selectedCalendarIdentifier];
I don't know exactly why it occurs but I guess it happens when you don't have any shared calendar in your device. Here is a link About shared iCloud calendars
I found the solution here and i fixed it in my app with next code snippet:
EKCalendar *selectedCalendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:self.eventStore];
NSString *selectedCalendarIdentifier = [[NSUserDefaults standardUserDefaults] objectForKey:#"selectedCalendarIdentifier"];
//instead of getting calendar by identifier
//get all calendars and check matching in the cycle
NSArray *allCalendars = [self.eventStore calendarsForEntityType:EKEntityTypeEvent];
for (EKCalendar *calendar in allCalendars) {
if ([calendar.calendarIdentifier isEqualToString:selectedCalendarIdentifier]) {
selectedCalendar = calendar;
break;
}
}
Off course it's not very good way but error disappeared.
Hope it will help you ;)
Another cause for this error is to use the bit mask EKEntityMaskEvent instead of the type EKEntityTypeEvent for the entity type parameter creating the calendar.
If you try to create the calendar such as:
EKCalendar *calendar = [EKCalendar calendarForEntityType:EKEntityMaskEvent eventStore:self.eventStore];
Then the calendar is well returned with an identifier, but the calendar seems not to be valid and it cannot be saved although no error is get. No event cannot be added to it. And the calendarWithIdentifier returns nil.
The right syntax is using EKEntityTypeEvent such as:
EKCalendar *calendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:self.eventStore];
Old question but, for reference, I had this problem when I switched from working with Reminders to Calendar events. I forgot to change the entity type in all the places.
Specifically, I was loading the status of my permissions for EKEntityTypeReminder with
EKAuthorizationStatus authorizationStatus = [EKEventStore authorizationStatusForEntityType:EKEntityTypeReminder];
and latter asking the user permission for EKEntityTypeEvent with
[self.eventStore requestAccessToEntityType:EKEntityTypeEvent completion:^(BOOL granted, NSError *error) {
if (error == nil) {
// Store the returned granted value.
} else {
NSLog(#"%#", [error localizedDescription]);
}
}];
So, the solution was to change the checking of status of my permissions to this:
EKAuthorizationStatus authorizationStatus = [EKEventStore authorizationStatusForEntityType:EKEntityTypeEvent];
I have trouble reporting achievements. I would like to do the following:
When I submit an achivment progress like 1%, I would like to increase the actuall progress not replaccing it.
So if I submit 1% and the user allready have like 4% its have to be 5% not 1%. Is there any way to do this?
Here my actual reporting code:
+(void)reportachivementwithidenfitier:(NSString *)identifier percentcompleted:(float)percent{
NSUserDefaults *defaults=[NSUserDefaults standardUserDefaults];
if ([defaults boolForKey:#"localplayeravailable"]) {
GKAchievement *achievement = [[GKAchievement alloc] initWithIdentifier: identifier];
if (achievement)
{
achievement.percentComplete = percent;
achievement.showsCompletionBanner=YES;
NSArray *achivments=[[NSArray alloc]initWithObjects:achievement,nil];
[GKAchievement reportAchievements:achivments withCompletionHandler:^(NSError *error){
if (error!=nil) {
NSLog(#"Achievement Submission failed with error:%#",[error description]);
}
else
{
NSLog(#"Achievement Succesfully reported");
}
}];
}
}
on this line:
achievement.percentComplete = percent;
you are setting it to a new value. Simply add the value to it, like so:
achievement.percentComplete += percent;
I am trying to get all the pictures of an album. I am getting this by an webservice. The webservice has the following layout.
{
"name": "Club Brugge - KRC Genk",
"date": "08.10.2012",
"albumId: 1,
"pictures": [
{
"pic_album_id"=1,
"pic_id" = 1,
"url": "http://www.krcgenk.be/images/gallery/album_199/800X600/1a06dc0e405fd0219e3d327f1eec7fbf.jpg"
},
{
"pic_album_id"=1,
"pic_id" = 2,
"url": "http://www.krcgenk.be/images/gallery/album_199/800X600/e8e10c0664eb0533a0534ed69891b165.jpg"
},
{
"pic_album_id"=1,
"pic_id"= 3,
"url": "http://www.krcgenk.be/images/gallery/album_199/800X600/750b55a87b8eae33b8f3278add9bec44.jpg"
}
]
I have the following functions to get all pictures of a certain album.
- (NSMutableArray *)getAllPicturesOfAlbumId: (int)AlbumId
{
NSString *picture_Url = [[NSString alloc]init];
NSArray *results = [[NSArray alloc]init];
_picturesForAlbum = [[NSMutableArray alloc]init];
picture_Url = #"";
NSFetchRequest *request = [[NSFetchRequest alloc] init];
NSPredicate *predicate = [NSPredicate predicateWithFormat:#"pic_album_id == %#",
[NSNumber numberWithInt:AlbumId]];
NSLog(#"album id: %#",[NSNumber numberWithInt:AlbumId]);
[request setEntity:[NSEntityDescription entityForName:#"Picture" inManagedObjectContext:self.genkDatabase.managedObjectContext]];
[request setPredicate:predicate];
NSError *error = nil;
results = [self.genkDatabase.managedObjectContext executeFetchRequest:request error:&error];
NSLog(#"results: %#",results);
if (results == nil) {
NSLog(#"nil results");
// handle errors
} else if (results.count == 0) {
NSLog(#"0 results");
// nothing found
} else {
for(int i = 0; i < results.count ; i++){
Picture *picture = [results objectAtIndex:i];
NSLog(#"%#",[results objectAtIndex:i]);
[_picturesForAlbum addObject:picture];
}
}
NSLog(#"%#",_picturesForAlbum);
//NSLog(#"album: %#",[_picturesForAlbum objectAtIndex:5]);
return _picturesForAlbum;
}
The code above, gives the following log. (I gave for testcase AlbumId = 3 with it)
2012-10-12 14:53:04.577 RacingGenk[4793:c07] album id: 3
2012-10-12 14:53:04.578 RacingGenk[4793:c07] results: (
)
2012-10-12 14:53:04.578 RacingGenk[4793:c07] (
)
Hope anybody can help me.
Kind regards.
** Here you see a screenshot of my database model
EDIT
Here you see how I get my pictures and put it in my database.
+ (Picture *)pictureWithGenkInfo:(NSDictionary *)genkInfo
inManagedObjectContext:(NSManagedObjectContext *)context
withAlbumId:(int)albumId
withPictureId:(int)pictureId;
{
Picture *picture = nil;
picture = [NSEntityDescription insertNewObjectForEntityForName:#"Picture"
inManagedObjectContext:context];
picture.url = [genkInfo objectForKey:PICTURES_URL];
picture.pic_album_id = [NSNumber numberWithInt:albumId];
picture.picture_id = [NSNumber numberWithInt:pictureId];
return picture;
}
//The method above is called in my first controller that comes one screen. With this loop I fill up my core data-base.
for (NSDictionary *genkInfo in albums ) {
albumId++;
[Album albumWithGenkInfo:genkInfo inManagedObjectContext:document.managedObjectContext withAlbumId:albumId];
for (NSDictionary *genkInfo2 in pictures ) {
pictureId++;
[Picture pictureWithGenkInfo:genkInfo2 inManagedObjectContext:document.managedObjectContext withAlbumId:albumId withPictureId:pictureId];
}
pictureId = 0;
// table will automatically update due to NSFetchedResultsController's observing of the NSMOC
}
Use predicate
[NSPredicate predicateWithFormat:#"whichAlbum.album_id == %d", AlbumId];
UPDATE
for (NSDictionary *genkInfo in albums ) {
albumId++;
Album *album = [Album albumWithGenkInfo:genkInfo inManagedObjectContext:document.managedObjectContext withAlbumId:albumId];
for (NSDictionary *genkInfo2 in pictures ) {
pictureId++;
Picture *pic = [Picture pictureWithGenkInfo:genkInfo2 inManagedObjectContext:document.managedObjectContext withAlbumId:albumId withPictureId:pictureId];
[album addPictureObject:pic]; // this method should be automatically generated
}
pictureId = 0;
// table will automatically update due to NSFetchedResultsController's observing of the NSMOC
}
// don't forget save context
How to troubleshoot:
Get yourself Liya or another sqlite database viewer. Navigate to the folder with the core data database. On the simulator that would be
/Users/<username>/Library/Application Support/iPhone Simulator/<version of iOS>/Applications/<long cryptig string>/<folder-with-the-core-data-database>
Open the sqlite database, navigate to the ZPicture table and check that data is present.
If there is no data then the the webservice -> core-data program logic has a problem.
If there is data and it appears to be good go back to Xcode and enable logging for the core-data request. Edit the scheme (Product - Edit scheme), select the Run, Debug scheme and change the tab to Arguments. In the field Arguments Passed On Launch add -com.apple.CoreData.SQLDebug 3. Ensure the check box is ticked.
Run your app and in the debugger console window there should be the sql code generated by core-data.
You will see something similar to: (you might see the whichAlbum showing up)
<timestamp> CoreData: annotation: fetch using NSSQLiteStatement <0xfxxxxxx> on entity
'Picture' with sql text 'SELECT 0, t0.Z_PK, t0.Z_OPT, t0.zpic_album_id
FROM zpicture t0 WHERE t0.zpic_album_id == ?'
<timestamp> CoreData: details: SQLite bind[0] = (int64)3
Take the sql command, return to Liya and paste the command into the Run Custom Command field. Replace the question mark in
t0.zpic_album_id == ?
with the album_id you want to see.
The result of the query will be what Core Data will retrieve.
Not sure where the whichAlbum would go. Just come back with your finding and let us know.