How can I pass additional data in my notifications im currently using Onesignal to send notification. im not sure if im using the key additionalData to send the additional data. I receive the notification but I do not receive the additional Data
//my custom completion handler to retrieve user token
self.getUserInfoCustom(userIdSearching: sendNotifToUser, completion: { (userInfo) in
// send notif
if let notif = userInfo?.deviceToken {
let value:NSMutableDictionary = [:]
value["include_player_ids"] = [notif]
value["contents"] = ["en": "Test Message"]
let additionalData = ["name":"Pierre"]
value["additionalData"] = additionalData
OneSignal.postNotification((value as NSDictionary) as! [AnyHashable:Any])
}
})
Instead of using additionalData, just use data
Related
I am working on adding Remote push notification support in my OSX application. I can successfully receive the push notification in my PC via apns and when I click the notification banner this is the behavior I am seeing.
If my app is not running , it will launch the application. But never hits on "ReceivedRemoteNotification()". Is this expected behavior ? Is there any way to receive the apns payload in this case ?
If my app is running I get the payload via "ReceivedRemoteNotification" and things are working fine.
So we cannot get apns payload in our app if it is not running?
Any help really appreciated.
thanks,
Jithesh
Figured it out. The payload is available through "NSNotification" parameter of DidFinishLaunching.
public override void DidFinishLaunching(NSNotification notification)
{
var uInfo = notification.UserInfo;
if(uInfo["NSApplicationLaunchUserNotificationKey"] != null)
{
var payLoad = uInfo["NSApplicationLaunchUserNotificationKey"] as NSUserNotification;
if(payLoad.ActivationType == NSUserNotificationActivationType.ActionButtonClicked)
{
NSAlert alert = new NSAlert();
alert.MessageText = "Button Clicked";
alert.RunModal();
}
var userInfo = payLoad.UserInfo;
//not.ActivationType ==
if (userInfo != null && userInfo.ContainsKey(new NSString("aps")))
{
//Get the aps dictionary
NSDictionary aps = userInfo.ObjectForKey(new NSString("aps")) as NSDictionary;
if (aps.ContainsKey(new NSString("content")))
{
var deepLink = (aps[new NSString("content")] as NSString).ToString();
NSAlert alert = new NSAlert();
alert.MessageText = deepLink;
alert.RunModal();
//DisplaySubView(deepLink);
//Console.WriteLine($"Deeplink : {deepLink}");
}
}
}
Is there a iOS notification that we get in ServiceManager (QMServicesManager), chatService to notify the app that a new Dialog is added for the user. Basically a brand new chat request
You could use QuickBlox's System notifications to send the message to the recipient after creating a dialog
let message: QBChatMessage = QBChatMessage()
let params = NSMutableDictionary()
params["event_type"] = "NewDialogCreated"
params["dialogId"] = <dialogId or the information you need to pass>
message.customParameters = params
message.recipientID = UInt(recipientId)!
QBChat.instance.sendSystemMessage(message) { (Error) in
}
and recipient could receive this message in QBChatdelegate
#pragma mark QBChatDelegate
func chatDidReceiveSystemMessage(message: QBChatMessage!) {
}
I checked OneSignal documentation but I couldn't understand clearly as beginner how setting dictionary as a post notification's additional data (like postID, userID, type) in iOS Native SDK using Swift to decide and redirect when user interacted with notification.
For posting I'm doing only like that:
OneSignal.sendTag("username", value: "\(user)")
OneSignal.postNotification(["contents": ["en": "#\(user) added an additive to your '\(title)' experience: \"\(strLast)\""],
"include_player_ids": [postOwnerPlayerID],
For receiving:
OneSignal.initWithLaunchOptions(launchOptions, appId: "______", handleNotificationReceived: nil, handleNotificationAction: {
(result) in
// This block gets called when the user reacts to a notification received
let payload = result?.notification.payload
//Try to fetch the action selected
if let additionalData = payload?.additionalData {
print("payload")
print(additionalData)
}
// After deciding which action then I can redirect user..
let username: String? = UserDefaults.standard.string(forKey: KEY_UID)
if username != nil {
if let tabbarController = self.window!.rootViewController as? UITabBarController {
tabbarController.selectedViewController = tabbarController.viewControllers?[2]
// NotificationCenter.default.post(name: Foundation.Notification.Name(rawValue: "notificationsUp"), object: nil)
}
}
}, settings: [kOSSettingsKeyInFocusDisplayOption : OSNotificationDisplayType.none.rawValue])
You set the data field as a key in the dictionary passed to OneSignal.postNotification like the following.
OneSignal.postNotification(["contents": ["en": "Test Message"],
"include_player_ids": ["3009e210-3166-11e5-bc1b-db44eb02b120"],
"data": ["postID": "id"]])
Then you need to get ready your keys from additionalData from the payload in the handleNotificationAction function.
if let additionalData = payload?.additionalData {
let postID: String? = additionalData["postID"]
}
Example from iOS in objC to send additional data...
[OneSignal postNotification:#{#"contents":#{#"en":text},
#"include_player_ids":oneSignalIds,
#"data":#{#"key": #"value"},
}];
And to receive the data...
[OneSignal initWithLaunchOptions:launchOptions
appId:ONESIGNAL_APPID
handleNotificationReceived:^(OSNotification *notification) {
if (notification.payload.additionalData) {
NSDictionary* additionalData = notification.payload.additionalData;
if (additionalData[#"key"]){
NSLog(#"Received Data - %#", additionalData[#"key"]);
}
}
}
handleNotificationAction:nil
settings:#{kOSSettingsKeyInAppAlerts:#YES}];
Hope it helps someone :)
Thanks to #jkasten helped me in the right direction! helped me get rid of the AnyHashable warning I was getting.
Swift 3 code (change PATH to the additionalData parameter you want to output):
let PATH = notification!.payload.additionalData["PATH"]
print("PATH: ",PATH as Any)
If you're looking to do the same but in the Notification Service Extension, take a look at our updated documentation.
The Notification Service Extension is used for:
- Badges
- Influenced Opens with Firebase Analytics
- Media Attachments
- Action Buttons
When I send a message using iOS to a PubNub channel, I can use the didReceiveMessage function to get that message and put it in my tableView. However, if I send a message via a client in the Dev Dashboard, message.data.message returns nil after I try to cast it as a String. Here's the function in question:
func client(client: PubNub, didReceiveMessage message: PNMessageResult) {
print("Received: %", message.data.message)
let newMessage:String? = message.data.message as? String
print(newMessage) // returns nil
self.messagesArray.append(newMessage!)
dispatch_async(dispatch_get_main_queue()) {
self.messageTableView.reloadData()
}
}
I get the following response in console from print("Received: %", message.data.message):
Received: % Optional({
text = test;
})
However, print(newMessage) is returning nil. What am I doing wrong?
Thanks!
EDIT: I'm getting the same thing when I try to get messages from the historyForChannel function.
//get history
pubNub.historyForChannel("channelname" as String, withCompletion: { (result, status) -> Void in
print(status)
if status == nil {
if result!.data.messages.count > 0 {
let historyMessages = result!.data.messages.description as? [String]
print(result)
for item in historyMessages!{
self.messagesArray.append(item)
}
}
}
})
historyMessages is nil, even though result prints:
Optional({
Operation = History;
Request = {
Authorization = "not set";
Method = GET;
Origin = "pubsub.pubnub.com";
"POST Body size" = 0;
Secure = YES;
URL = "...redacted";
UUID = "...redacted";
};
Response = {
"Processed data" = {
end = 14609023551682481;
messages = (
"technically ",
{
text = "Well..ok then";
},
hi,
"really ",
{
text = "Well..ok then";
},
How do I get the text from these returned messages?
From behaviour and fact what history fetch printed out status object means what you probably configured your client with cipherKey. That status object which you receive probably has category set to decryption error.
If you want to use encryption - you should use same key for all clients, or they won't be able to decrypt sent messages. If cipherKey is set, client automatically try to decrypt data and it will fail if regular text has been received.
Make sure both (console and iOS client) configured with same cipherKey or if you don't need it, make sure what it not set on any of clients.
Best regards,
Sergey.
I am new to swift . I used APAdressBook Framework for retrieving contacts in iPhone .Every thing working fine up to IOS 8.4 but when checked in IOS 9 of Simulator and iPhone devices it is not accessing contacts and even it not showing alert message like would you like to access contacts any one can face this type of problem if yes please give me your valuable answer?
Apple Inc. introduce Contacts.framework from iOS 9. So, it would be better use this framework to retrieve contacts.
Here is way to fetch email or whole contact from Contacts app.
Add Contacts.framework to your project.
Create or add new file of type header and give name like yourProjectName-Bridging-Header.h write #import <Contacts/Contacts.h> statement into file and save and set appropriate path of this file from build setting.
Now create method
func getAllContacts() {
let status = CNContactStore.authorizationStatusForEntityType(CNEntityType.Contacts) as CNAuthorizationStatus
if status == CNAuthorizationStatus.Denied {
let alert = UIAlertController(title:nil, message:"This app previously was refused permissions to contacts; Please go to settings and grant permission to this app so it can use contacts", preferredStyle:UIAlertControllerStyle.Alert)
alert.addAction(UIAlertAction(title:"OK", style:UIAlertActionStyle.Default, handler:nil))
self.presentViewController(alert, animated:true, completion:nil)
return
}
let store = CNContactStore()
store.requestAccessForEntityType(CNEntityType.Contacts) { (granted:Bool, error:NSError?) -> Void in
if !granted {
dispatch_async(dispatch_get_main_queue(), { () -> Void in
// user didn't grant access;
// so, again, tell user here why app needs permissions in order to do it's job;
// this is dispatched to the main queue because this request could be running on background thread
})
return
}
let arrContacts = NSMutableArray() // Declare this array globally, so you can access it in whole class.
let request = CNContactFetchRequest(keysToFetch:[CNContactIdentifierKey, CNContactEmailAddressesKey, CNContactBirthdayKey, CNContactImageDataKey, CNContactPhoneNumbersKey, CNContactFormatter.descriptorForRequiredKeysForStyle(CNContactFormatterStyle.FullName)])
do {
try store.enumerateContactsWithFetchRequest(request, usingBlock: { (contact:CNContact, stop:UnsafeMutablePointer<ObjCBool>) -> Void in
let arrEmail = contact.emailAddresses as NSArray
if arrEmail.count > 0 {
let dict = NSMutableDictionary()
dict.setValue((contact.givenName+" "+contact.familyName), forKey: "name")
let emails = NSMutableArray()
for index in 0...arrEmail.count {
let email:CNLabeledValue = arrEmail.objectAtIndex(index) as! CNLabeledValue
emails .addObject(email.value as! String)
}
dict.setValue(emails, forKey: "email")
arrContacts.addObject(dict) // Either retrieve only those contact who have email and store only name and email
}
arrContacts.addObject(contact) // either store all contact with all detail and simplifies later on
})
} catch {
return;
}
}
}
Call this method where you want self.getAllContacts()
And when you want to retrieve
for var index = 0; index < self.arrContacts.count; ++index {
let dict = self.arrContacts[index] as! NSDictionary
print(dict.valueForKey("name"))
print(dict.valueForKey("email"))
}