Here is what I added in my iOS app:
- (void) schedule:(CDVInvokedUrlCommand*)command
{
NSArray* notifications = command.arguments;
[self.commandDelegate runInBackground:^{
for (NSDictionary* options in notifications) {
APPNotificationContent* notification;
notification = [[APPNotificationContent alloc]
initWithOptions:options];
notification.title = #"This is title2";
notification.subtitle = #"This is subtitle";
notification.body = #"This is body";
notification.categoryIdentifier = #"demoCategory";
NSLog(#"categoryIdentifier: %#", notification.categoryIdentifier);
NSString* found;
found = [_center hasActionGroup:notification.categoryIdentifier] ? #"yes" : #"no";
NSLog(#"category existance: %#", found);
[self scheduleNotification:notification];
}
[self check:command];
}];
}
And here is what I received when it was triggered:
2022-12-09 13:11:12.595804+1300 MyApp[71182:11636137] NotificationCenter Handle push from foreground
2022-12-09 13:11:12.595994+1300 MyApp[71182:11636137] Notification received
2022-12-09 13:11:12.596147+1300 MyApp[71182:11636137] Push Plugin key: alert
2022-12-09 13:11:12.626052+1300 MyApp[71182:11637337] categoryIdentifier: demoCategory
2022-12-09 13:11:12.627402+1300 MyApp[71182:11637337] category existance: yes
I added two buttons in that category, but I ended up receiving a notification without any action button.
Is the categoryIdentifier not working? Or should I somehow check if the category is applied correctly?
Related
I've done as the guide says
This is the message manager
[GNSMessageManager setDebugLoggingEnabled:YES];
messageManager = [[GNSMessageManager alloc] initWithAPIKey:API_KEY paramsBlock:^(GNSMessageManagerParams *params) {
params.bluetoothPowerErrorHandler = ^(BOOL hasError) {
// Update the UI for Bluetooth power
};
params.bluetoothPermissionErrorHandler = ^(BOOL hasError) {
// Update the UI for Bluetooth permission
};
}];
These are my methods to publish and subscribe with the Nearby API.
- (IBAction)onPublish:(id)sender {
NSLog(#"publish");
NSString* str = #"hello world";
NSData* data = [str dataUsingEncoding:NSUTF8StringEncoding];
GNSMessage* message = [GNSMessage messageWithContent:data];
id<GNSPublication> publication = [messageManager publicationWithMessage:message paramsBlock:^(GNSPublicationParams *publicationParams) {
publicationParams.strategy = [GNSStrategy strategyWithParamsBlock:^(GNSStrategyParams * strategyParams) {
strategyParams.allowInBackground = YES;
strategyParams.discoveryMediums = kGNSDiscoveryMediumsBLE;
strategyParams.discoveryMode = kGNSDiscoveryModeDefault;
}];;
}];
}
- (IBAction)onSubscribe:(id)sender {
NSLog(#"subscribe");
id<GNSSubscription> subscription = [messageManager subscriptionWithMessageFoundHandler:^(GNSMessage *msg) {
// Add the name to a list for display
NSLog(#"message found %#", [msg description]);
} messageLostHandler:^(GNSMessage *msg) {
// Add the name to a list for display
NSLog(#"message lost %#", [msg description]);
} paramsBlock:^(GNSSubscriptionParams *subscriptionParams) {
subscriptionParams.strategy = [GNSStrategy strategyWithParamsBlock:^(GNSStrategyParams * strategyParams) {
strategyParams.allowInBackground = YES;
strategyParams.discoveryMediums = kGNSDiscoveryMediumsBLE;
strategyParams.discoveryMode = kGNSDiscoveryModeDefault;
}];;
}];
}
Both Bletooth central and peripheral background capabilities are enabled, and the permission string for the peripheral is set.
Finally I subscribe on an iOS device and publish from another one but nothing happens.
Be sure to retain the publication and subscription objects. They stop publishing/subscribing when they're deallocated. The usual way is to store them as properties/ivars in one of your classes.
The developer docs are misleading on this point, and I apologize. We'll improve the docs in the next release.
When I receive data from a socket and pass the data to another VC via NSNotificationCenter, the passed object always logs (null), despite the object being present in the other class.
there is where I pass the data through.
UPDATED:
-(void) initSIOSocket {
[SIOSocket socketWithHost:#"http://192.168.1.4:8080" response:^(SIOSocket *socket) {
self.socket = socket;
NSLog(#"%# from initSIOSocket", self.socket);
[self.socket on:#"q_update_B" callback:^(NSArray *args) {
NSArray *tracks = [args objectAtIndex:0];
[[NSNotificationCenter defaultCenter] postNotificationName:#"qUpdateB" object:nil userInfo:[NSDictionary dictionaryWithObject:tracks forKey:#"tracksData"]];
}];
..
- (void)receiveUpdateBNotification:(NSNotification *)notification
{
// Do parse respone data method and update yourTableViewData
NSArray *tracks = [[notification userInfo] objectForKey:#"tracksData"];
NSLog(#"%#", tracks);
self.tracks = tracks;
[self.tableView reloadData];
}
Console is STILL logging as (null) object. The notification is successful, no data is sent.
For passing data using NSNotification you need to use the userInfo dictionary.
Post it like:
[[NSNotificationCenter defaultCenter] postNotificationName:#"qUpdateB" object:nil userInfo:[NSDictionary dictionaryWithObject:tracks forKey:#"MyData"]];
And retrieve it using:
- (void)receiveUpdateBNotification:(NSNotification *)notification
{
self.tracks = [[notification userInfo] objectForKey:#"MyData"];
[self.tableView reloadData];
}
Object property is not intended for passing data.
object
The object associated with the notification. (read-only) Declaration
#property(readonly, retain) id object Discussion;
This is often the object that posted this notification. It may be nil.
Typically you use this method to find out what object a notification
applies to when you receive a notification.
For example, suppose you’ve registered an object to receive the
message handlePortDeath: when the “PortInvalid” notification is posted
to the notification center and that handlePortDeath: needs to access
the object monitoring the port that is now invalid. handlePortDeath:
can retrieve that object as shown here:
- (void)handlePortDeath:(NSNotification *)notification
{
...
[self reclaimResourcesForPort:notification.object];
...
}
Reference
I needed to use my Singleton to pass the data using the NSNotificationCenter, like so.
-(void) initSIOSocket {
[SIOSocket socketWithHost:#"http://192.168.1.4:8080" response:^(SIOSocket *socket) {
self.socket = socket;
NSLog(#"%# from initSIOSocket", self.socket);
[self.socket on:#"q_update_B" callback:^(NSArray *args) {
NSArray *tracks = [args objectAtIndex:0];
self.setListTracks = tracks;
[[NSNotificationCenter defaultCenter] postNotificationName:#"qUpdateB" object:nil];
}];
}];
}
..
- (void)receiveUpdateBNotification:(NSNotification *)notification
{
if ([[notification name] isEqualToString:#"qUpdateB"])
NSLog (#"Successfully received the test notification!");
// Do parse respone data method and update yourTableViewData
NSArray *tracks = [[SocketKeeperSingleton sharedInstance]setListTracks];
self.tracks = tracks;
[self.tableView reloadData];
}
I was using the calendar code from Apple Sample Code.
I want to make my calendar in the app to add events.
But I am not getting the how to make the own calendar and add it to the default calendar app of iOS.
I am getting this error.
"Terminating app due to uncaught exception 'NSGenericException', reason: 'Can't directly init a calendar. Use calendarWithEventStore"
-(void)performCalendarActivity:(EKEventStore*)evtStore
{
On using
// find local source
EKSource *localSource = nil;
for (EKSource *source in self.eventStore.sources) {
if (source.sourceType == EKSourceTypeLocal) {
localSource = source;
break;
}
}
// Get the default calendar from store.
// self.defaultCalendar = [self.eventStore defaultCalendarForNewEvents];
self.defaultCalendar = [[EKCalendar alloc]init];
// self.defaultCalendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:self.eventStore];
self.defaultCalendar.CGColor = [UIColor blueColor].CGColor;
self.defaultCalendar.title = #"MyNEWCalForApp";
// self.defaultCalendar.allowsContentModifications = YES;
self.defaultCalendar.source = localSource;
NSError* error1;
[self.eventStore saveCalendar:self.defaultCalendar commit:YES error: &error1];
NSLog(#"error:%#",error1);
NSLog(#"save cal id = %#", self.defaultCalendar.calendarIdentifier);
[[NSUserDefaults standardUserDefaults] setObject:self.defaultCalendar.calendarIdentifier forKey:#"CalendarIdentifier"];
[[NSUserDefaults standardUserDefaults] synchronize];
self._calIdentifier = [[NSUserDefaults standardUserDefaults]valueForKey:#"CalendarIdentifier"];
NSLog(#"existing cal id = %#", [[NSUserDefaults standardUserDefaults]valueForKey:#"CalendarIdentifier"]);
self.defaultCalendar = [self.eventStore calendarWithIdentifier:_calIdentifier];
self.eventsList = [[NSMutableArray alloc] initWithArray:0];
// Fetch today's event on selected calendar and put them into the eventsList array
[self.eventsList addObjectsFromArray:[self fetchEventsForToday]];
[self.tableView reloadData];
}
*----EDIT----**
ON USING:
self.defaultCalendar = [EKCalendar calendarForEntityType:EKEntityTypeEvent eventStore:self.eventStore];
On adding the event and on delegate call
// Overriding EKEventEditViewDelegate method to update event store according to user actions.
- (void)eventEditViewController:(EKEventEditViewController *)controller
didCompleteWithAction:(EKEventEditViewAction)action {
NSError *error = nil;
EKEvent *thisEvent = controller.event;
switch (action) {
case EKEventEditViewActionCanceled:
// Edit action canceled, do nothing.
break;
case EKEventEditViewActionSaved:
// When user hit "Done" button, save the newly created event to the event store,
// and reload table view.
// If the new event is being added to the default calendar, then update its
// eventsList.
if (self.defaultCalendar == thisEvent.calendar) {
[self.eventsList addObject:thisEvent];
}
if (self.defaultCalendar == thisEvent.calendar) {
is never true.
Please help.
I didn't have this problem with fb SDK 3.2, but after I upgraded it in SDK 3.5.1 friend inviter has some strange problem, when I select one friend it choose the selected one and the one under it. Also when I am trying to scroll downward it restarts the table and brings me back on the tables top.
Here is my method:
-(IBAction)secondClick:(id)sender
{
NSDictionary *params = [[NSDictionary alloc] initWithObjectsAndKeys:nil];
[FBWebDialogs
presentRequestsDialogModallyWithSession:nil
message:#"Learn how to make your iOS apps social."
title:#"Test"
parameters:params
handler:^(FBWebDialogResult result, NSURL *resultURL, NSError *error) {
if (error) {
// Error launching the dialog or sending the request.
NSLog(#"Error sending request.");
} else {
if (result == FBWebDialogResultDialogNotCompleted) {
// User clicked the "x" icon
NSLog(#"User canceled request.");
} else {
// Handle the send request callback
NSDictionary *urlParams = [self parseURLParams:[resultURL query]];
if (![urlParams valueForKey:#"request"]) {
// User clicked the Cancel button
NSLog(#"User canceled request.");
} else {
// User clicked the Send button
NSString *requestID = [urlParams valueForKey:#"request"];
NSLog(#"Request ID: %#", requestID);
}
}
}
}];
From what i have come to know is that facebook has fixed this issue and is going to make the fix live soon.
An alternate solution to this is to make your own custom UI.
1. Get Friends List - [self startConnectionWithGraphPath:#"me/friends" parameters:params method:#"GET" completionSelector:#selector(callback)]
Download pictures using url #"https://graph.facebook.com/fbid/picture"
Implement a table view similar to facebook's request ui showing list of friends along with their profile pics.
Use 'to' param to direct the request to the selected user(s). NSMutableDictionary* params = [NSMutableDictionary dictionaryWithObjectsAndKeys: #"286400088", #"to", nil];
This way you won't need to show facebook ui to select friends. Al though the UI will still appear after user selects friends from your custom UI, but that'd be just to tap 'send'.
One way is to use the Facebook friendPicker
https://developers.facebook.com/ios/friendpicker-ui-control/
And then take the facebook id's result of that and put them into the requestdialog just like Nitin said.
I'll post my friendPicker code:
- (IBAction)inviteFriendsClicked:(id)sender {
// Initialize the friend picker
FBFriendPickerViewController *friendPickerController =
[[FBFriendPickerViewController alloc] init];
// Set the friend picker title
friendPickerController.title = #"Välj vänner";
// TODO: Set up the delegate to handle picker callbacks, ex: Done/Cancel button
// Load the friend data
[friendPickerController loadData];
// Show the picker modally
[friendPickerController presentModallyFromViewController:self
animated:YES
handler:
^(FBViewController *sender, BOOL donePressed) {
if(donePressed) {
NSString *userString;
userString = #"";
int *counter = 0;
for (id<FBGraphUser> user in friendPickerController.selection) {
NSLog(user.id);
NSMutableArray *userArray = [[NSMutableArray alloc] init];
[userArray addObject:user.id];
if(counter == 0){
userString = user.id;
}else{
userString = [NSString stringWithFormat:#"%#%#%#", userString, #",", user.id];
}
counter++;
}
if(counter != 0){
[self requestDialog: userString]; // Display the requests dialog and send the id-string with it
}
// NSLog(#"Selected friends: %#", friendPickerController.selection);
}
}];
}
I use a facebook api to connect to facebook and send request via native dialogs provided by the api.
I followed the sample posted in the docs on developers.facebook.com
But I have following problem sending requests :
1. The requests are not shown in notifications - only in application center - In this case i think that it is a problem of that the app is in sandbox and not posted to APPSTORE
I succesfully send request to facebook server with right fbUser id. But when I want to receive the notification in app here comes the problem :
Following the docs as an authorized user I should se
this in open url method:
fb[APP_ID]://authorize#expires_in=[ACCESS_TOKEN_EXPIRATION]
&access_token=[USER_ACCESS_TOKEN]
&target_url=https://apps.facebook.com/[APP_NAME_SPACE]/?request_ids=
[COMMA_SEPARATED_REQUESTIDs]&ref=notif&app_request_type=user_to_user
But i can see only plain login without targer url .... I can see session expiration date, fb app id, access token and so on. But no target url?
So basically what the target_url is?
How it should be set?
What i have to include when sending request?
In addition :
application handle open url method is called properly.
checkRequests method is also called properly after app becomes active.
Please do not link me to the docs. I have read it moreless 50 times and didn't find any reasonable solution...
- (BOOL)application:(UIApplication *)application
openURL:(NSURL *)url
sourceApplication:(NSString *)sourceApplication
annotation:(id)annotation {
// attempt to extract a token from the url
self.openedURL = url;
NSLog(#"%#",url);
return [FBSession.activeSession handleOpenURL:url];
}
- (void)sendRequest {
FBSBJSON *jsonWriter = [FBSBJSON new];
NSDictionary *gift = [NSDictionary dictionaryWithObjectsAndKeys:
#"5", #"points",
#"1", #"badge",
nil];
NSString *giftStr = [jsonWriter stringWithObject:gift];
NSMutableDictionary* params =
[NSMutableDictionary dictionaryWithObjectsAndKeys:
#"Hi from test app", #"message",
giftStr, #"data",
nil];
[self.facebook dialog:#"apprequests"
andParams:params
andDelegate:self];
}
// Handle the request call back
- (void)dialogCompleteWithUrl:(NSURL *)url {
NSDictionary *params = [self parseURLParams:[url query]];
NSString *requestID = [params valueForKey:#"request"];
NSLog(#"Request ID: %#", requestID);
}
-(FBSession*)returnSession{
return self.session;
}
/*
* Helper function to get the request data
*/
- (void) notificationGet:(NSString *)requestid {
[FBRequestConnection startWithGraphPath:requestid
completionHandler:^(FBRequestConnection *connection,
id result,
NSError *error) {
if (!error) {
NSString *title;
NSString *message;
if ([result objectForKey:#"data"]) {
title = [NSString
stringWithFormat:#"%# sent you a gift",
[[result objectForKey:#"from"]
objectForKey:#"name"]];
FBSBJSON *jsonParser = [FBSBJSON new];
NSDictionary *requestData =
[jsonParser
objectWithString:[result objectForKey:#"data"]];
message =
[NSString stringWithFormat:#"Badge: %#, Karma: %#",
[requestData objectForKey:#"badge"],
[requestData objectForKey:#"points"]];
} else {
title = [NSString
stringWithFormat:#"%# sent you a request",
[[result objectForKey:#"from"] objectForKey:#"name"]];
message = [NSString stringWithString:
[result objectForKey:#"message"]];
}
UIAlertView *alert = [[UIAlertView alloc]
initWithTitle:title
message:message
delegate:nil
cancelButtonTitle:#"OK"
otherButtonTitles:nil,
nil];
[alert show];
// Delete the request notification
[self notificationClear:[result objectForKey:#"id"]];
}
}];
}
/*
* Helper function to check incoming URL
*/
- (void) checkIncomingNotification {
if (self.openedURL) {
NSString *query = [self.openedURL fragment];
if (!query) {
query = [self.openedURL query];
}
NSDictionary *params = [self parseURLParams:query];
for (NSString * str in [params allKeys]) {
NSLog(#"key %#", str);
}
// Check target URL exists
NSString *targetURLString = [params valueForKey:#"target_url"];
if (targetURLString) {
NSURL *targetURL = [NSURL URLWithString:targetURLString];
NSDictionary *targetParams = [self parseURLParams:[targetURL query]];
NSString *ref = [targetParams valueForKey:#"ref"];
// Check for the ref parameter to check if this is one of
// our incoming news feed link, otherwise it can be an
// an attribution link
if ([ref isEqualToString:#"notif"]) {
// Get the request id
NSString *requestIDParam = [targetParams
objectForKey:#"request_ids"];
NSArray *requestIDs = [requestIDParam
componentsSeparatedByString:#","];
// Get the request data from a Graph API call to the
// request id endpoint
[self notificationGet:[requestIDs objectAtIndex:0]];
}
}
// Clean out to avoid duplicate calls
self.openedURL = nil;
}
}
Is there any way that these problems are caused by the way that the app is not published on Appstore (Appstore id is not set neither for iPhone nor iPad)?
Here are code snippets showing using of the fb api:
Thank you very much for the time.
Enable deep linking in Facebook app settings
Facebook sdk 3.5 requests not working
I think this link will help you,configure App on Facebook as well