How to mark notification as read after I receive cloud kit response? - ios

From CloudKit I receive example response:
[AnyHashable("aps"): {
"content-available" = 1;
}, AnyHashable("ck"): {
ce = 2;
cid = "iCloud.pl.blueworld.fieldservice";
nid = "bb501155-f914-4f8b-b58e-4c24921727f5";
qry = {
dbs = 2;
fo = 3;
rid = "27C8C222-11B3-4831-A125-EAFEF8DB6ADD";
sid = "E32D6B20-3F81-464E-ACA8-2DD29FA93CF3";
zid = "_defaultZone";
zoid = "_defaultOwner";
};
}]
At any time I can fetch missed notifications and mark them as read to prevent from receiving it again.
Simply I do it like this:
OperationQueue().addOperation(CKMarkNotificationsReadOperation(notificationIDsToMarkRead: [queryNotification.notificationID!]))
nid field links to notification connected with this response.
After I receive CloudKit response I need to mark this notification as read. All I have is String, but operation to mark it as read expects CKNotificationID object. How can I create such object?

Related

IOS push notifications not being grouped - apn

I am using apn push notificaitons from node server.
I want to group same nature of notifications together.
For that I am using threadId parameter but its still not grouping the notifications.
Here is my server side code:
var apnOptions = {
token: {
key: "certificates/F5TRRQ26V.p8",
keyId: "F5TRRQ26V",
teamId: "4ZGSRKDXH"
},
production: false
};
var apnProvider = new apn.Provider(apnOptions);
var note = new apn.Notification();
note.expiry = Math.floor(Date.now() / 1000) + 3600; // Expires 1 hour from now.
note.badge = 3;
note.sound = "ping.aiff";
note.alert = "\uD83D\uDCE7 \u2709 You have a new message";
note.payload = { 'messageFrom': 'John Appleseed' };
note.topic = "com.example.myapp";
note.threadId = "870";
apnProvider.send(note, '5DA3C319EB50GDDGGAAA333DC9FE6DB240C34C66CBF1E547CD8307DCA15').then( (result) => {
console.log(result);
});
On IOS app side I am receiving this:
User Info = [AnyHashable("thread-id"): 870, AnyHashable("threadId"): 870, AnyHashable("aps"): {
alert = "\Ud83d\Udce7 \U2709 You have a new message";
badge = 3;
sound = "ping.aiff";
"thread-id" = 870;
}, AnyHashable("messageFrom"): John Appleseed]
But still the notifications are not being grouped.

Push Notifications using Firebase/Google Cloud Functions

I am trying to send a notification when a number is written to _random. I am able to get the device token, and the cloud function works perfectly. However, I do not receive the notification on the simulator. I am using the notification token that is pushed to Firebase to test with. If anybody can help, it will be highly appreciated.
https://i.stack.imgur.com/OB94c.png
const functions = require('firebase-functions');
const admin = require('firebase-admin');
admin.initializeApp(functions.config().firebase);
//Initial function call:
exports.makeRandomFigures = functions.https.onRequest((req, res) => {
    //create database ref
    var rootRef = admin.database().ref();
    var doc_count_temp = 0;
    var keys = [];
    var random_num = 0;
    //get document count
    rootRef.once('value', (snapshot) => {
        doc_count_temp = snapshot.numChildren();
        //real number of member. if delete _timeStamp then minus 2 not 3!
        var doc_count = doc_count_temp - 3;
        //get num array previous generated
        var xRef = rootRef.child("_usedFigures");
        xRef.once('value', function(snap) {
            snap.forEach(function(item) {
                var itemVal = item.val();
                keys.push(itemVal);
            });
            //get non-duplicated random number
            var is_equal = true;
            while (is_equal) {
                random_num = Math.floor((Math.random() * doc_count) + 1);
                is_equal = keys.includes(random_num);
            }
            //insert new random vaule to _usedFigures collection
            rootRef.child('_usedFigures').push(random_num);
            rootRef.child('_random').set(random_num);
        });
    });
    //send back response
    res.redirect(200);
});
exports.sendFigureNotification = functions.database.ref('_random').onWrite(event => {
const payload = {
notification: {
title: 'Title',
body: `Test`, //use _random to get figure at index key
badge: '1',
sound: 'default'
}
};
const options = {
priority: "high",
timeToLive: 60 * 60 * 24, //24 hours
content_available: true
};
const token = "cge0F9rUTLo:APA91bGNF3xXI-5uxrdj8BYqRPkxUPA5x9IQALtm3VEFJAdV2WQrQufNkzIclT5B671mBcvR6IDMbgSKyL7iG2jAuxRM3qR3MXhkNp1_utlXhCpE2VZqTw6Yw3d4iMMvHl1B-Cvik6NY";
console.log('Sending notifications');
return admin.messaging().sendToDevice(token, payload, options);
});
You can't get push notifications on the simulator.
To try some alternative ways check this link :
How can I test Apple Push Notification Service without an iPhone?

FCM custom notification for ios

I know this question have been ask a lot of time in android but not ios. So I already test out push notification with FCM it work fine. Mine problem is wether it's a way to create custom notification rather than letting the system to handle the notification with the notification payload?
-Users can send data messages with FCM.What you have to send is,
Sample PostMan Json data:
{ "data": {
"any key": "any value",
"any key 2": "any value 2"
},
"to" : "token received to mobile from FCM"
}
Payload inside "data" can change according to the requirement.
Mobile end:
application(_:didReceiveRemoteNotification:) override method will get fire.So it is unto developer to extract data from the userInfo property in iOS and use it.
For ios using c# working code:-
public bool NotificationToiosDevice()
{
bool str;
try
{
//Create the web request with fire base API
WebRequest tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "post";
//serverKey - Key from Firebase cloud messaging server
tRequest.Headers.Add(string.Format("Authorization: key={0}", "AAAALNl-P7o:APA91bE38khU73UTdIj7L6LvVS3uI6f47REmxl.................................."));
//Sender Id - From firebase project setting
tRequest.Headers.Add(string.Format("Sender: id={0}", "12345"));
tRequest.ContentType = "application/json";
var payload = new
{
to = "dDDbFltwE5o:APA91bFmZZ-c1pNp................",
priority = "high",
content_available = true,
notification = new
{
title = "Title Of Notification",
},
data = new
{
body = new { Parameter1 = "FirstParameterValue", Parameter2 = "SecondParameterValue" },
},
};
string jsonNotificationFormat = Newtonsoft.Json.JsonConvert.SerializeObject(payload);
Byte[] byteArray = Encoding.UTF8.GetBytes(jsonNotificationFormat);
tRequest.ContentLength = byteArray.Length;
using (Stream dataStream = tRequest.GetRequestStream())
{
dataStream.Write(byteArray, 0, byteArray.Length);
using (WebResponse tResponse = tRequest.GetResponse())
{
using (Stream dataStreamResponse = tResponse.GetResponseStream())
{
if (dataStreamResponse != null) using (StreamReader tReader = new StreamReader(dataStreamResponse))
{
String sResponseFromServer = tReader.ReadToEnd();
// str = sResponseFromServer;
}
}
}
}
str = true;
}
catch (Exception ex)
{
str = false;
}
return str;
}

How can I send a Firebase Cloud Messaging notification to iOS device without use the Firebase Console?

If I send notification to iOS device from FCM console I am getting the message alert on notification center (swipe down from the Top of the screen to view Notification Centre).
didRecievedRemoteNotification Output is :
{
aps = {
alert = "From console";
};
"gcm.message_id" = "0:1470206236110595%b2c76869b2c76869";
"gcm.n.e" = 1;
"google.c.a.c_id" = 2979094970349938289;
"google.c.a.e" = 1;
"google.c.a.ts" = 1470206236;
"google.c.a.udt" = 0;
}
But if send notification to iOS device I am sending using api from my server I am not receiving message alert on notification center (swipe down from the Top of the screen to view Notification Centre).
didRecievedRemoteNotification Output is :
{
"collapse_key" = "do_not_collapse";
from = 67981113117;
message = "alert from api";
time = "03-08-2016 12:44:53";
}
My API code is which is in C#:
string RegIDs = "some id";
var appID = "some id";
var SenderID = "some id";
var value = Text1.Text;
WebRequest tRequest;
tRequest = WebRequest.Create("https://fcm.googleapis.com/fcm/send");
tRequest.Method = "POST";
tRequest.ContentType = "application/x-www-form-urlencoded;charset=UTF-8";
tRequest.Headers.Add(string.Format("Authorization: key={0}", appID));
tRequest.Headers.Add(string.Format("Sender: id={0}", SenderID));
//Data_Post Format
// string postData = "{'collapse_key' : 'demo', 'registration_id': [ '" + regId + "' ],
//'data': {'message': '" + Label1.Text + "'},'time_to_live' : '3' }";
//json for android
string postData = "collapse_key=score_update&time_to_live=108&delay_while_idle=1&data.message="
+ value + "&data.time=" + System.DateTime.Now.ToString() + "&registration_id=" + RegIDs + "";
Console.WriteLine(postData);
Byte[] byteArray = Encoding.UTF8.GetBytes(postData);
tRequest.ContentLength = byteArray.Length;
Stream dataStream = tRequest.GetRequestStream();
dataStream.Write(byteArray, 0, byteArray.Length);
dataStream.Close();
WebResponse tResponse = (WebResponse)tRequest.GetResponse();
dataStream = tResponse.GetResponseStream();
StreamReader tReader = new StreamReader(dataStream);
String sResponseFromServer = tReader.ReadToEnd();
Label3.Text = sResponseFromServer; //printing response from GCM server.
tReader.Close();
dataStream.Close();
tResponse.Close();
Another alternative in order to test push notifications without using Firebase console is using Postman. Attached two images with configuration details.
Image 1: Set notification payload
Image 2: Set request headers ( Content-Type and Authorization )
Firebase push notification endpoint: https://fcm.googleapis.com/fcm/send

Play sound for remote notifications

i try to play a sound for remote notifications. the app is registered for remoteNotificatiosTypeSound, the sound is enable in notifications phone settings.
the structure of remote notification is like that in console:
{
aps = {
alert = "Notification received";
badge = 1;
payload = {
action = A;
date = "2014-09-16";
idmessage = 243722;
message = "";
time = "11:39:33";
title = "";
};
sound = alarm4.wav;
};
}
It is an error somewhere?
Thank you
sound = alarm4.wav
Does the device have this sound file?
Try
"sound": "default"
Also, this should be a JSON string so you should have : instead of =

Resources