Showing posts with label push-notification. Show all posts
Showing posts with label push-notification. Show all posts

Saturday, October 13, 2018

Does iOS throttle scheduled local push notifications?

Leave a Comment

My app receives silent push notifications via FCM, as I see in the logging the are received and handled. What my app then does is decide to some logic if a notification is shown to the user or not. This sometimes works, sometimes doesn't. It seems to me as if it works first and then suddenly stops working, so I'm guessing if it may be a throttling problem?

I do schedule 5 notifications 30 seconds apart - so the user does not miss the notification:

    for i in 0...5 {         let notification = UNMutableNotificationContent()         notification.title = NSLocalizedString("bed_wet", comment: "")         notification.subtitle = device.lookAfterPatientString         notification.sound = UNNotificationSound(named: "alarm.mp3")         notification.categoryIdentifier = Notification.Category.alarm         notification.userInfo = ["identifier": device.id]          let timeInterval = max(1, delaySeconds) + i * 30         let notificationTrigger = UNTimeIntervalNotificationTrigger(timeInterval: TimeInterval(timeInterval), repeats: false)         let request = UNNotificationRequest(identifier: UUID.init().uuidString, content: notification, trigger: notificationTrigger)          UNUserNotificationCenter.current().add(request) { error in             ...         }     } 

can this loop be the problem?

1 Answers

Answers 1

Try it with dispatch_async, Several code that not blocking main thread maybe called and some times not called.

The second problem is maybe iOS have logic that prevent an app to spam the phone. Have u seen instagram notification limited from maybe hundred to only several notification.

Thanks

Read More

Saturday, September 1, 2018

onNotification() is not fired when app is killed

Leave a Comment

i'm using https://github.com/zo0r/react-native-push-notification to get push notifications and the onNotification is working as aspected when the app is Active or in the Background i'm receiving the notification, but when i kill the app i only get the notification and the onNotification is not fired can any one please help i searched for a solution but nothing worked, i'm increasing the Android badges count when the onNotification is fired is there another way to increasing Android badges when the app is killed?

"react-native": "0.55.3", "react-native-push-notification": "3.0.2" 

my code

const options = {         // (optional) Called when Token is generated (iOS and Android)         onRegister: (token) => {             this._TOKEN = token.token;             this._addToPushChannels(channel);         },          onNotification: (notification) => {             console.log(notification);             if (notification['foreground']) {              }              //Notification from the background or when the app is killed             if (!notification['foreground']) {                 if (Platform.OS !== 'ios' && Platform.Version < 26) {                     this._messageCount++;                     // console.log('this._messageCount ', this._messageCount);                     let BadgeAndroid = require('react-native-android-badge');                     BadgeAndroid.setBadge(this._messageCount);                 }             }              // required on iOS only (see fetchCompletionHandler docs: https://facebook.github.io/react-native/docs/pushnotificationios.html)             notification.finish(PushNotificationIOS.FetchResult.NewData);          },          // ANDROID ONLY: GCM Sender ID (optional - not required for local notifications, but is need to receive remote push notifications)         senderID: this._SENDER_ID,          // IOS ONLY (optional): default: all - Permissions to register.         permissions: {             alert: true,             badge: true,             sound: true         },          // Should the initial notification be popped automatically         // default: true         popInitialNotification: true,          /**          * (optional) default: true          * - Specified if permissions (ios) and token (android and ios) will requested or not,          * - if not, you must call PushNotificationsHandler.requestPermissions() later          */         requestPermissions: true,      };      PushNotification.configure(options); 

2 Answers

Answers 1

I am not positive but when I remember correctly killing (alias force closing) an app disables the onNotification functionality in Android (GCM) Push Notification Gateway (unlike iOS/APNS). This is a Android-wise feature and intentionally created so that users who willingly force close their app dont get "bothered" with notifications. The Xtify service will be restarted and messages will be received when either the phone is restarted or the app is reopened.

What you could do is schedule notifications apriori. WhatsApp, for instances, frequently posts notifications like: "You may have new notifications" when the app is forced closed to remind the user to reopen the app.

References:

Answers 2

[1] https://stackoverflow.com/a/37845174/3607191

[2] https://stackoverflow.com/a/47857531/3607191

[3] https://github.com/dluksza/react-native-push-notification/commit/5bb95881c27b0068249c0f68bbf65e54a565fa3d#diff-54ebb78785872f03fd8e71ed2dfed620R18

You can invoke headless function on JS side to update the batch count, following is what you have to do. Here, the catch is you've to write some Java code.

  1. As explained in [2] you have to write a service extending FirebaseMessagingService.
  2. Write one more service by extending HeadlessJsTaskService to invoke headless JS function. Refer RNPushNotificationActionService.java file of [3].
  3. Now, as explained in [1] within onMessageReceived function of the service, call the native service you wrote in step 2 to invoke headless JS function. To know how to do, refer RNPushNotificationActionHandlerReceiver.java file of [3].
Read More

Monday, August 13, 2018

Replicate SNS Topic subscription from one device end point to another

Leave a Comment

I have an android device that is registered to an SNS Platform Application. So it is a platform endpoint (in terms of aws sns). It has subscribed a total of 20 Sns Topics.

If I have another device (Android or Iphone), which is also an SNS platform endpoint, I would like it to be subscribed to same SNS topics.

Basically, I want to subscribe sns topics from one device. And if I install this application to another device, I want all of my subscription to be replicated on that other device as well. I hope I made my self clear.

I am using AWS SDK for Asp.net core.

Thanks for helping out.

1 Answers

Answers 1

Essentially for GCM another device would require another subscription.

The logic below will not work automatically unless you program it in your application.

Basically, I want to subscribe sns topics from one device. And if I install this application to another device, I want all of my subscription to be replicated on that other device as well. I hope I made my self clear.

Please check this example in mobile-platform-endpoint documentation, it is not the same scenario but can be used as reference.

Read More

Sunday, July 29, 2018

How to remove new Notifications from banner?

Leave a Comment

Is there any way to handle remote notification payloads before they’re delivered and display in notification centre?

1 Answers

Answers 1

With push notifications of default type there is no way to filter out notifications if the app is not in foreground.

The possible solution to this is to use VoIP push notifications in conjunction with PushKit.

VoIP pushes are always waking up the application, however they are not presented to the user and don't modify app badge value, so it's up to the developer to show a local notification upon the received VoIP push and to deal with app badge.

There is a technique with additional silent push that for example Facebook is using, to delete notification on iOS device when the message has been read on desktop web site. It's described here: https://www.pushwoosh.com/docs/deletable-ios-push

Read More

Thursday, May 17, 2018

Safari Push Notifications can't be allowed

Leave a Comment

I'm trying to implement safari push notifications on my site using this guide https://developer.apple.com/library/content/documentation/NetworkingInternet/Conceptual/NotificationProgrammingGuideForWebsites/PushNotifications/PushNotifications.html

There is a button on the site and the following JS code:

window.onload = function() {                                                                                                  var p = document.getElementById('subscribe');                                                                               p.onclick = function() {                                                                                                      // Ensure that the user can receive Safari Push Notifications.                                                              if ('safari' in window && 'pushNotification' in window.safari) {                                                              var permissionData = window.safari.pushNotification.permission('MY_REAL_WEBSITE_PUSH_ID');              checkRemotePermission(permissionData);                                                                                    }                                                                                                                         };                                                                                                                           var checkRemotePermission = function(permissionData) {                                                                        console.log(permissionData);                                                                                                if (permissionData.permission === 'default') {                                                                                // This is a new web service URL and its validity is unknown.                                                               window.safari.pushNotification.requestPermission(                                                                             'MY_REAL_WEBSERVICE_URL', // The web service URL.                                                      'MY_REAL_WEBSITE_PUSH_ID',     // The Website Push ID.                                                  {}, // Data that you choose to send to your server to help you identify the user.                                           checkRemotePermission         // The callback function.                                                                   );                                                                                                                        }                                                                                                                           else if (permissionData.permission === 'denied') {                                                                            // The user said no.                                                                                                      }                                                                                                                           else if (permissionData.permission === 'granted') {                                                                           // The web service URL is a valid push provider, and the user said yes.                                                     // permissionData.deviceToken is now available to use.                                                                    }                                                                                                                         };                                                                                                                        } 

As a result when I press the button I get request permission.

When I disallow notifications all works as expected: console.log(permissionData); shows permissionData.permission equals denied and I can see site as denied at Safari's Preferences -> Notifications section.

But when I allow notification nothing happens. It seems checkRemotePermission doesn't fire as window.safari.pushNotification.requestPermission's callback.

Any thoughts?

1 Answers

Answers 1

I had a similar problem in a virtual machine, and found a solution for VMWare.

In the configuration .vmx file, you need add something like this:

smbios.reflectHost = "TRUE" serialNumber = "RM125589AGW" board-id = "MAC-F22598C8" 
Read More

Friday, March 16, 2018

UNNotificationRequest plays custom sound only when iPhone is unlocked

Leave a Comment

My app is downloading a .wav file and moving it to Library/Sounds, then scheduling a local notification via UNNotificationRequest with that sound's file name. This request sends notifications as expected, but the custom sound I have added only plays aloud when the phone is unlocked, not when the notification is getting delivered to the phone's lock screen. However, if I use UNNotificationSound.default() instead of my custom sound, the default push sound will play both on the lock screen and when the device is unlocked. Anyone have any ideas what could be causing this issue? My code is simple:

let soundName = "demoSound.wav" // (or nil to use default)  let center = UNUserNotificationCenter.current() center.removeAllPendingNotificationRequests()  let content = UNMutableNotificationContent() content.title = "Title" content.body = "Body"; content.sound = soundName.flatMap { UNNotificationSound(named: $0) } ??  UNNotificationSound.default()  let trigger = UNTimeIntervalNotificationTrigger(timeInterval: 60, repeats: true) let identifier = "PushNotifierLocalNotification" let request = UNNotificationRequest(identifier: identifier, content: content, trigger: trigger) center.add(request, withCompletionHandler: nil) 

EDIT: this isn't a problem for bundled sounds (dragged & dropped into Xcode), but I see the above issue only when I use sounds downloaded by my app and moved into Library/Sounds.

1 Answers

Answers 1

From here, you will notice that :

Waveform Audio File Format (WAVE, or more commonly known as WAV due to its filename extension - both pronounced "wave"[6])3[7][8][9] (rarely, Audio for Windows)[10] is a Microsoft and IBM audio file format standard for storing an audio bitstream on PCs.

I assume that Apple prefer native Apple sound format, like AIFF or CAF, which are both developped by Apple.

May you retry with an AIFF or or CAF sound file format and confirm use if the issue is still here ?

You may also take a look here .

Read More

Friday, November 24, 2017

Clear notifications badge without removing notifications

Leave a Comment

In my app, I'm receiving push notifications with badge number set to one. When app will start, it should set badges count to 0, so I'm using:

[[UIApplication sharedApplication] setApplicationIconBadgeNumber:0]; 

And it works, but also it removes all notifications from notifications center.
Is there a way to clear badges without removing notifications?

3 Answers

Answers 1

According to this topic:

How to clear badge number while preserving notification center

setting:

[[UIApplication sharedApplication] setApplicationIconBadgeNumber:-1]; 

should do the trick.

Answers 2

With iOS9 directly setting badge to negative still clears notifications. You must fire empty UILocalNotification with negative badgenumber to achieve this.

let ln = UILocalNotification() ln.applicationIconBadgeNumber = -1 UIApplication.sharedApplication().presentLocalNotificationNow(ln) 

Answers 3

@feb for ios 9+ you need to set 0 not -1 for that you need to add version condition

    if #available(iOS 9.0, *) {         UIApplication.shared.applicationIconBadgeNumber = 0     }else{         UIApplication.sharedApplication().applicationIconBadgeNumber = -1     } 
Read More

Saturday, November 4, 2017

WhatsApp VoIP Push non-delivery and iOS 11

Leave a Comment

There's lots of problems with push in general in iOS 11.0n. I have two apps, one uses silent pushes and I can reproduce problems with the pushes not being delivered. Theres nothing I can do to fix it, its an Apple issue, they have changed the behavior of silent pushes and also introduced a bug with iOS 11.0.

However I also have another app which uses VoIP push. WhatsApp uses VoIP push and their users have been experiencing lots of notification issues with iOS 11.0n too: https://whatsappen.com/news/5465/many-complaints-whatsapp-notifications-ios-11-update-solution

That link above (and WhatsApp web site states something sililar)

It’s indeed an iOS 11 bug. It is affecting users who habitually force close their app.

I'm unable to reproduce any similar issue with my app which uses VoIP push (tried force quitting it several times). And that's my problem - the fact that I can't reproduce it. Just because I can't reproduce it doesn't mean it doesn't affect my app.

If there is a problem with VoIP push and therefore potentially with my app's behavior I would like to reproduce it, and fix it. WhatsApp claim they fixed their issue without waiting for a new release from Apple, so it must be something they can work around.

I would like to know if anybody knows what this VoIP push problem is with WhatsApp and what they did to fix it.

0 Answers

Read More

Monday, July 31, 2017

Android push notification banner not showing up in some devices

Leave a Comment

I tried to push notify with NotificationCompat :

NotificationCompat.Builder b = new NotificationCompat.Builder(this);             b.setAutoCancel(true)                     .setDefaults(NotificationCompat.DEFAULT_ALL)                     .setWhen(System.currentTimeMillis())                     .setSmallIcon(this.getResources().                         getIdentifier("ic_launcher", "mipmap", this.getPackageName()))                     .setLargeIcon(BitmapFactory.decodeResource(this.getResources(),                         this.getResources().                         getIdentifier("ic_launcher", "mipmap", this.getPackageName())))                     .setTicker("God Reacts")                     .setVisibility(NotificationCompat.VISIBILITY_PUBLIC)                     .setPriority(Notification.PRIORITY_MAX)                     .setContentTitle(data.get("lineOne"))                     .setContentText(data.get("lineTwo"))                     .setContentInfo("Spread the message !");              PendingIntent contentIntent = PendingIntent.getActivity(this, 0,                     new Intent(this,getMainActivityClass()),                     PendingIntent.FLAG_UPDATE_CURRENT);             b.setContentIntent(contentIntent);             NotificationManager nm = (NotificationManager)              this.getSystemService(Context.NOTIFICATION_SERVICE);             nm.notify(1, b.build()); 

But in few devices (Samsung,MI etc) the notification banner is not shown. The notification slides in the action tray with sound and vibrate.

But in few devices it is shown perfectly when the app is closed/background/foreground.The device where it's popping up correctly uses marshmallow.Is is due to specific OS ? Or is it device related issue? What extra I need to add?

3 Answers

Answers 1

The problem may arise in some devices of nougat version due to Battery optimization.
eg. Samsung Galaxy S8 and S8+, Oneplus, xaiomi etc. but in Android version of nougat, You can try this once, for that you have to check settings once,

step 1: Goto settings >

step 2: search for "Battery optimization" >

step 3: from here, tap on "apps not optimized" and switch to "all apps."

step 4: search for your app (of which you are not getting notification)

step 5: tap on your app name and set it as not optimized so that it can receive notification.

OR

step 1: Go to Settings > Apps

step 2: Click the : Menu in top right, select > [Special Access]

step 3: Select > Optimize Battery Usage >

step 4: Click the dropdown menu towards the top of the screen that says: "Apps not optimized [v]" -> change to [All Apps]

step 5: select your app and change it "Not optimized".

Answers 2

in chinese devices like MI or OPPO ,etc . The system shut downs notification services for non-whitelisted apps .So there is nothing much you can do about it . Simply request them to whitelist your app ( bleak chance of happening in general ) or use a hack of always keeping your app in memory somehow , say by running some blank background service 24*7

Answers 3

First Try with minimum notification property . Try following code which is working fine in my app . If it works than you can debug your code by enabling on by one property of notification .

 private void sendNotification(String messageBody) { Intent intent = new Intent(this, NotificationActivity.class);     intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);      PendingIntent pendingIntent = PendingIntent.getActivity(this, 0 /* Request code */, intent,             PendingIntent.FLAG_ONE_SHOT);      Uri defaultSoundUri= RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION);     NotificationCompat.Builder notificationBuilder = new NotificationCompat.Builder(this)             .setSmallIcon(R.drawable.ic_action_notification)             .setContentTitle("Touchrooms Notification")             .setContentText(messageBody)             .setAutoCancel(true)             .setSound(defaultSoundUri)             .setContentIntent(pendingIntent);      NotificationManager notificationManager =             (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);      notificationManager.notify(0 /* ID of notification */, notificationBuilder.build());  } 
Read More

Tuesday, June 20, 2017

Execute module after POST request

Leave a Comment

I'm trying to integrate sending real-time information via sockets (using socket.io), and sending push notifications using the OneSignal platform.

It happens that if I put everything in the same module, I do not know why the method to send the notification is not executed after the information is sent, or before sending the information.

If I run the command npm start no error appears but the notification arrives as soon as the local or remote server is running, and this way I do not want it to happen.

user.js

  var express = require('express'); var router = express.Router(); var misocket = require('../routes/misocket'); var notificacion = require('../routes/notificacion');  /*  run module when start server run, i don't want it  notificacion();  */   /* GET users listing. sendnote*/ router.post('/sendasig', function(req, res, next) {        console.log(misocket);//registrednote     misocket.emit("registrar",req.body);     //run here, after the send data across post request   notificacion();     console.log(req.body);    res.status(200).json({       message  : "send message"   });   });  module.exports = router; 

notificacion.js

 module.exports = function(){           var OnesignalNotificationApi = require('onesignal-notification');         var api = new OnesignalNotificationApi('N2FkY2ZkZWQtMGQ2MS00ZTUwLTlkM2QtODA2NmE0YjBiMzQ3',                                         'c4b92cce-4d59-4550-a4be-20939370e39c');          var message = {                 it: 'Some message',                 en: 'Some message',                 es: 'Nueva Calificacion'         };          api.sendToAll(message, null, function(err, res){                 console.log(err);                 console.log(res);         });   };  

index.js

var express = require('express'); var router = express.Router();  /* GET home page. */ router.get('/', function(req, res, next) {   res.render('index', { title: 'Express' }); });  module.exports = router; 

misocket.js

var i = 0; var ioapp;  exports.connection= function(io){      ioapp = io;      io.on('connect',function(s){         console.log("Conectado");         });  };  exports.io = ioapp; 

3 Answers

Answers 1

In your notification.js File the sendToAll function will be executed when the file is required (which is probably at run time for you.)

api.sendToAll(message, null, function(err, res){     console.log(err);     console.log(res); });  

You're going to want to wrap this in a function and call it inside of your post route.

module.exports = function(message){    api.sendToAll(message, null, function(err, res){      console.log(err);       console.log(res);    });  } 

Which can then be required at the top of your server

 const sendMessageFunction = require('path/to/notification.js')  .  .  .  sendMessageFunction('helloWorld') 

Answers 2

Replace Your notification.js with the below code

 module.exports = function(){       var sendNotification = function (data) {     var headers = {         "Content-Type": "application/json; charset=utf-8",         "Authorization": "Basic N2FkY2ZkZWQtMGQ2MS00ZTUwLTlkM2QtODA2NmE0YjBiMzQ3"     };      var options = {         host: "onesignal.com",         port: 443,         path: "/api/v1/notifications",         method: "POST",         headers: headers     };      var https = require('https');     var req = https.request(options, function (res) {         res.on('data', function (data) {             console.log("Response:");             console.log(JSON.parse(data));         });     });      req.on('error', function (e) {         console.log("ERROR:");         console.log(e);     });      req.write(JSON.stringify(data));     req.end(); };  var message = {     app_id: "c4b92cce-4d59-4550-a4be-20939370e39c",     contents: {"en": "sample message"},     included_segments: ["All"] };  sendNotification(message);  };  

Answers 3

Did you try editing user.js to be like this:

var express = require('express'); var router = express.Router(); var misocket = require('../routes/misocket'); var notificacion = require('../routes/notificacion');  var OnesignalNotificationApi = require('onesignal-notification'); var api = new OnesignalNotificationApi('N2FkY2ZkZWQtMGQ2MS00ZTUwLTlkM2QtODA2NmE0YjBiMzQ3',                                     'c4b92cce-4d59-4550-a4be-20939370e39c');   /* GET users listing. sendnote*/ router.post('/sendasig', function(req, res, next) {      console.log(misocket);//registrednote     misocket.emit("registrar",req.body);       //run here, after the send data across post request     notificacion(api);     console.log(req.body);      res.status(200).json({         message  : "send message"     });  });  module.exports = router; 

and notification.js to be like this:

module.exports = function(api){       var message = {             it: 'Some message',             en: 'Some message',             es: 'Nueva Calificacion'     };      api.sendToAll(message, null, function(err, res){             console.log(err);             console.log(res);     });   }; 
Read More

Monday, June 19, 2017

AWS Mobile HUD AWS SNS pushManagerDidRegister but endpoint not created

Leave a Comment

I am using AWS Mobile HUD with AWS SNS and am running into problems.

What works / was done already

  • sucessfully created p12 universal certificate
  • resources on AWS SNS created sucessfully by Mobile HUD
  • topic created sucessfully by Mobile HUD
  • integrated code into project
  • integrated plist

the following code should register the app (device) with AWS SNS:

pushManager = AWSPushManager(forKey: ServiceKey) pushManager?.delegate = self pushManager?.registerForPushNotifications() 

and - greatly enough func pushManagerDidRegister(_ pushManager: AWSPushManager) is called, indicating success. My func pushManagerDidRegister(_ pushManager: AWSPushManager) looks as fo

func pushManagerDidRegister(_ pushManager: AWSPushManager) {     print("Successfully enabled Push Notifications on platform: \(pushManager.platformARN)")     // Subscribe the first topic among the configured topics (all-device topic)     if let defaultSubscribeTopic = pushManager.topicARNs?.first {         let topic = pushManager.topic(forTopicARN: defaultSubscribeTopic)         topic.subscribe()     } } 

log output:

Successfully enabled Push Notifications on platform: Optional("arn:aws:sns:eu-central-1:00000000:app/APNS/appname_MOBILEHUD_12345678") 

but: on AWS SNS resource no endpoint is created in this application / platformARN

Interesting facts (maybe the reason)

  • Build config is DEBUG
  • Logged platformARN is RELEASE and not DEBUG

edit: After playing around with different swift compiler flags I managed to set the environment correclty. Now i get logging that the registration was successfull on the Sandbox Environment. But: still no endpoint created on AWS SNS.

any ideas on how i could proceed? I tried for 2 days now including recertification, rebuilding AWS, endless logging ;)

2 Answers

Answers 1

so I looked for the issue in docs and their github. What I noticed that they are using AWSSNSCreatePlatformEndpointInput which you don't have, also you have to get device token from func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) and register it.

anyway it should be something like this

func application(application: UIApplication, didRegisterForRemoteNotificationsWithDeviceToken deviceToken: NSData) {  let deviceTokenString = "\(deviceToken)".stringByTrimmingCharactersInSet(NSCharacterSet(charactersInString:"<>"))     .stringByReplacingOccurrencesOfString(" ", withString: "") print("deviceTokenString: \(deviceTokenString)") NSUserDefaults.standardUserDefaults().setObject(deviceTokenString, forKey: "deviceToken") mainViewController()?.displayDeviceInfo()  let sns = AWSSNS.defaultSNS() let request = AWSSNSCreatePlatformEndpointInput() request.token = deviceTokenString request.platformApplicationArn = SNSPlatformApplicationArn sns.createPlatformEndpoint(request).continueWith(executor: AWSExecutor.mainThreadExecutor(), block: { (task: AWSTask!) -> AnyObject! in     if task.error != nil {         print("Error: \(task.error)")     } else {         let createEndpointResponse = task.result as! AWSSNSCreateEndpointResponse         print("endpointArn: \(createEndpointResponse.endpointArn)")         NSUserDefaults.standardUserDefaults().setObject(createEndpointResponse.endpointArn, forKey: "endpointArn")         self.mainViewController()?.displayDeviceInfo()     }      return nil }) } 

please, update me what happened and good luck

Answers 2

I found the answer here: AWS push notification service integration error

The issue was with missing privileges on AWS Mobile HUB. Sadly no sensible error was created ;)

Adding the policy AmazonSNSFullAccess solved it.

Read More

Sunday, June 11, 2017

Icon for push notification?

Leave a Comment

I am working on a chat app that receive push notification. I want to provide images/icon that will be used by iOS to display in push notification , where can I specify that in Xcode?

1 Answers

Answers 1

If you want to customize the appearance of local and remote notifications, perform the following steps:

  1. Create a UNNotificationCategory and add to the UNUserNotificationCenter category:

    let newCategory = UNNotificationCategory(identifier: "newCategory",                                          actions: [ action ],                                          minimalActions: [ action ],                                          intentIdentifiers: [],                                          options: [])  let center = UNUserNotificationCenter.current()  center.setNotificationCategories([newCategory]) 
  2. Create a UNNotificationContentExtension:

enter image description here

then use code or storyboard to customize your UIViewController.

  1. Add category to UNNotificationContentExtension's plist:

enter image description here

4.Push Notification

Local Notification

Create a UNMutableNotificationContent and set the categoryIdentifier to "newCategory" which includes UNUserNotificationCenter's categories and UNNotificationContentExtension's plist:

let content = UNMutableNotificationContent() content.title = ... content.body = ... content.categoryIdentifier = "newCategory"  let request = UNNotificationRequest.init(identifier: "newNotificationRequest", content: content, trigger: nil)  let center = UNUserNotificationCenter.current() center.add(request) 

Remote Notification

Set "mutable-content : 1" and "category : newCategory". Note that the category value is set to "newCategory" which matches what you previously added to UNUserNotificationCenter and UNNotificationContentExtensions plist.

Example:

 {     "aps" : {         "alert" : {         "title" : "title",         "body" : "Your message Here"         },         "mutable-content" : "1",         "category" : "newCategory"     },     "otherCustomURL" : "http://www.xxx.jpg"  } 
  1. Note: you need a device or simulator which supports 3DTouch, otherwise you can't show a custom UNNotificationContentExtension viewcontroller.(In iOS10 Beta1, it`s not work. But now this work without 3d touch)

And ... if you just want to show an image on a push notification displayed on the lock screen, you need to add UNNotificationAttachment:

let content = UNMutableNotificationContent() content.title = ... content.body = ... content.categoryIdentifier = "newCategory"  let fileURL: URL = ... //  your disk file url, support image, audio, movie  let attachement = try? UNNotificationAttachment(identifier: "attachment", url: fileURL, options: nil) content.attachments = [attachement!]  let request = UNNotificationRequest.init(identifier: "newNotificationRequest", content: content, trigger: nil)  let center = UNUserNotificationCenter.current() center.add(request) 

enter image description here

For more detail feature,Demo

Read More

Friday, April 21, 2017

iOS API to manage push notifications

Leave a Comment

This is a long shot, but are there any public (or private) API's that allow us to read existing push notifications on an iOS device? For example, can an app running in the background pole the system every X seconds to determine if the device has received a push notification from the Stack Exchange app and get it's contents?

The thought here is there are some services (such as the Ring Video Doorbell) that do not yet have public REST APIs. But when there is motion detected on the Ring camera, it sends a push notification. Similar to the popular IFTTT service, this app would pole for that notification on the device and then do something based on criteria set by the user.

I imagine there has to at least be a private API since Apple shows the device's recent notifications in the Notification Center.

4 Answers

Answers 1

Even if it was possible to use an unsupported API that violated app security, the contents of the push notification are encrypted and you may not be able to read the contents.

However, Apple's Developer site has information on relaying and interacting with other app's push notifications over bluetooth for a bluetooth ANCS.

"The purpose of the Apple Notification Center Service (ANCS) is to give Bluetooth accessories (that connect to iOS devices through a Bluetooth low-energy link) a simple and convenient way to access many kinds of notifications that are generated on iOS devices."

https://developer.apple.com/library/content/documentation/CoreBluetooth/Reference/AppleNotificationCenterServiceSpecification/Introduction/Introduction.html#//apple_ref/doc/uid/TP40013460-CH2-SW1

This may not be applicable to you, but it is Apple's approved method for interacting with, and relaying push notifications from other apps to bluetooth devices.

Answers 2

No, that's not possible. It seems that it will be a privacy issue if other apps will read other apps push notifications content.

Answers 3

Apple would never give such API private/Public, this will violate apps security.You can only read your apps push notifications.

if you use private API , there is good chance that your app will be rejected when you submit to app store.

some possible solutions to your app.

1) Figure out is there any way your app gets that push notification.

2) Or you have to use Inter-App Communication.

Answers 4

I interpret this question to be asking specifically in the lens of a IFTTT device that could already read/write data to a "standard" IFTTT app, and you're wondering how that's done. To me, that's the question, and not asking about a hacky private API push notification system.

With that in mind, the solution is generally referred to as HomeKit from what I know. It's one of Apple's "Kits", with general docs found here

What I think you're looking to do is more along the lines of database observation, where you're maybe looking to build some aggregator app of this data set stored on the device (which Apple has a standard method of asking users for permissions, and is fully allowed on the system just like Camera/Health/Photo permissions, etc).

Observing HomeKit database changes is found at a developer doc linked from the first, but found here

I haven't used this before myself, but from the docs, I can see there are methods for observation using regular old iOS KVO:

[[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updateHomes:) name:@"UpdateHomesNotification" object:nil]; [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(updatePrimaryHome:) name:@"UpdatePrimaryHomeNotification" object:nil];

There's a lot more info there, and I'm sure StackOverflow itself (and old WWDC videos of course) have lots of info on HomeKit. I hope this was the intended interpretation the question-asker meant. Similarly, though, each of the supported channels for events (HealthKit, MapKit, etc) can send you "push notification" type updates about what your user is doing with built-in APIs.

If you're attempting to simply read from other application's push payloads, then the other answers are correct and that is not possible on a pure privacy basis that Apple sandboxes your application: Apple Sandbox Docs Link

Read More

Wednesday, April 19, 2017

Notification Sound, Vibration and LED don't work

Leave a Comment

I'm trying to set custom Sound, Vibration and LED colors for the Notificaitons in my app - but it doesn't work. Everything else like setting the title, icon, color etc work fine. I've tried many solutions suggested in Stackoverflow but they didn't work either, so I'm asking a question.

Here is my notification code -

    Intent resultIntent = new Intent(this, ActivityB.class);     Bundle b = new Bundle();     //Some bundle related Code     resultIntent.putExtra("bundle",b);      TaskStackBuilder stackBuilder = TaskStackBuilder.create(this);     stackBuilder.addNextIntent(new Intent(this, ActivityA.class));     stackBuilder.addNextIntent(resultIntent);      PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0,PendingIntent.FLAG_UPDATE_CURRENT);      android.support.v7.app.NotificationCompat.Builder builder = new android.support.v7.app.NotificationCompat.Builder(this);     builder.setSmallIcon(R.drawable.ic_small_logo);     builder.setLargeIcon(BitmapFactory.decodeResource(getResources(), R.drawable.ic_logo_large));     builder.setContentTitle(notification.getTitle());     builder.setContentText(notification.getBody());     builder.setColor(Color.parseColor("#FFFFFF"));     builder.setStyle(new NotificationCompat.BigTextStyle());     builder.setVibrate(new long[] { 1000, 100, 1000, 100, 1000 });     builder.setLights(Color.YELLOW, 3000, 3000);     builder.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notif1));     builder.setAutoCancel(true);     builder.setContentIntent(resultPendingIntent);      NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);     notificationManager.notify(1, builder.build()); 

I have added permission for Vibration too. Tested this on 2 phones running Lollipop and Marshmallow.

Edit 1:

Sharing all the permissions that my application uses -

<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.INTERNET" /> <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" /> <uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE" /> <uses-permission android:name="android.permission.WAKE_LOCK" /> <uses-permission android:name="com.android.alarm.permission.SET_ALARM" /> <uses-permission android:name="android.permission.READ_CONTACTS" /> <uses-permission android:name="android.permission.RECEIVE_SMS" /> <uses-permission android:name="android.permission.READ_PHONE_STATE" /> <uses-permission android:name="android.permission.VIBRATE"/> 

Edit 2: Works on Marshmallow version phone. Does not work on Phones with Lollipop.

Edit 3: Works on Nougat too (One plus 3T Phone).

3 Answers

Answers 1

Based on your comments, it seems to be problem with your phone itself. I was asking in (1) regarding the vibration because you are setting { 1000, 100, 1000, 100, 1000 } which is a 1000 ms delay, followed by 100 ms vibration. This can be too little to detect.

Anyway, I had the same problem for vibration on some devices, so I used vibrator service directly instead. What I did was like this after issuing the notification. As per you comment below, I also added the ringtone manager section.

// built the notification without vibration and sound NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE); notificationManager.notify(1, builder.build()); // start vibrator manually Vibrator vibrator = (Vibrator) context.getSystemService(Context.VIBRATOR_SERVICE); vibrator.vibrate(new long[] {1000, 100, 1000, 100, 1000}, Constants.VIBRATION_ONCE); // start sound manually Uri uri = Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notif1); Ringtone ringtone = RingtoneManager.getRingtone(this, uri); ringtone.play(); 

This seems to work for most devices. As for the light of the notification, it is already stated in Official Document that

Set the desired color for the indicator LED on the device, as well as the blink duty cycle (specified in milliseconds). Not all devices will honor all (or even any) of these values.

If you are using Mi devices, try to "trust" the app and enable all permissions required for notifications, including "auto-start". It will work in most cases.

Answers 2

One of the reasons the sound does not work is because it cannot find the file change from builder.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.notif1)); to

String uriSound = String.format("android.resource://%s/raw/%s",getPackageName(), R.raw.notif1);

   builder.setSound(uriSound); 

For the lights use RGB combinations. builder.setLights(Color.rgb(130, 130, 130));

change the vibration pattern to something more uniform,

builder.setVibrate(new long[] { 50, 100, 150, 200, 250}); 

Answers 3

Try this one may be this help you out.

For Lights...

notification.ledARGB = 0xff00ff00; notification.ledOnMS = 300; notification.ledOffMS = 1000; notification.flags |= Notification.FLAG_SHOW_LIGHTS; 

For Vibration...

long[] vibrate = {0,100,200,300}; notification.vibrate = vibrate; 

Reference link 1

Read More

Wednesday, February 15, 2017

iOS push notification settings after reinstall

Leave a Comment

For iOS8 there is option when iOS cache push notification permission for 24h and after reinstall I would not receive push notification alert.

And there is workaround:

Resetting the Push Notifications Permissions Alert on iOS

The first time a push-enabled app registers for push notifications, iOS asks the user if they wish to receive notifications for that app. Once the user has responded to this alert it is not presented again unless the device is restored or the app has been uninstalled for at least a day.

If you want to simulate a first-time run of your app, you can leave the app uninstalled for a day. You can achieve the latter without actually waiting a day by following these steps:

Delete your app from the device. Turn the device off completely and turn it back on. Go to Settings > General > Date & Time and set the date ahead a day or more. Turn the device off completely again and turn it back on. Source: https://developer.apple.com/library/ios/technotes/tn2265/_index.html

Q: But for iOS9+ there is no cached push permission, and after reinstall I received alert every time. Is there any option to cache my choice for 24h and use it after reinstall ?

3 Answers

Answers 1

No.

Push Notifications permissions alert on iOS normally comes whenever we are registering our app for remote notification.

So once the behavior of permissions alert is changed by respective iOS version, we cant handle it by our own.

I hope this might help you.

Answers 2

Let's get a basic Understanding about Push Notifications for iOS 8.0 and iOS 9.0 Or Later.

Solution : 1

Resetting the Push Notifications Permissions Alert on iOS

The first time a push-enabled app registers for push notifications, iOS asks the user if they wish to receive notifications for that app. Once the user has responded to this alert it is not presented again unless the device is restored or the app has been uninstalled for at least a day.

If you want to simulate a first-time run of your app, you can leave the app uninstalled for a day. You can achieve the later without actually waiting a day by following these steps:

 1. Delete your app from the device.   2. Turn the device off completely and turn it back on.   3. Go to Settings > General > Date & Time and set the date ahead a day or more.   4. Turn the device off completely again and turn it back on. 

Solution : 2

You can also change your bundle ID over and over while debugging, each time notifications will get queried fresh. Once you are satisfied with code return to original bundle ID.

Source:

How to get back "Allow Push Notifications" dialog after it was dismissed once?

Answers 3

try setting up a new iCloud account and see if that was it because I had the same problem and so i tried it and the new one would push while the old one would only retrieve if the mail app was open. If that does not help I have contacted the apple software developers and they have not responded you may have to wait until the 9.1 update release.

Read More

Friday, April 22, 2016

Codename one push notifications with php issue

Leave a Comment

I've enabled push notifications in my app, added the build hints, registered the api on the play developer console, created and loaded the apple certificates on my server. When I test the app on a device it successfully registers for push notifications. However my issue comes in with trying to actually send a push notification. I want it to send through PHP. I use this code which is taken straight from the developer guide. However this does not work... Is it a problem with my code or did I do something wrong in the enabling push notifications process.

<?php  include("config.php");  $args = http_build_query(array( 'certPassword' => 'XXXXXXXX', 'cert'  =>    'http://kyven.co.za/mibrand/certificate/XXXX.p12', 'production' => false, 'device' => null, 'packageName' => 'za.co.bonyelo.mibrand', 'email'   =>      'kyri88@gmail.com', 'type' => 1, 'auth' => 'XXXXXXXXXXXXXXXXXXXXXXXXXX', 'body' => 'Test')); $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded',    'content'      => $args ) ); $context = stream_context_create($opts); $response = file_get_contents("https://codename-     one.appspot.com/sendPushMessage", false, $context);  die(json_encode($response)); ?> 

2 Answers

Answers 1

Got it. This is the code I used

<?php  include("config.php");  $args = http_build_query(array('token' => 'XXXXXXXXXXXXXXXXXXX', 'certPassword' => 'XXXXXXXX', 'cert' =>      'http://XXXXXXX/XXXXX/XXXXX/Certificates.p12', 'production' => false, 'device' => 'cn1-ios-XXXXXXXXXXXXXXXXXXXXXXXX',  'packageName' => 'za.co.bonyelo.mibrand', 'email' =>     'kyri88@gmail.com', 'type' => 1, 'auth' => 'XXXXXXXXXXX', 'body' => 'EAT MY BALLS'));  $opts = array('http' => array( 'method' => 'POST', 'header' => 'Content-type: application/x-www-form-urlencoded',    'content' => $args ) ); $context = stream_context_create($opts); $response =    file_get_contents("https://push.codenameone.com/push/push", false,    $context);  die(json_encode($response));   ?> 

Answers 2

I don't know PHP so I can't really help with the code. Notice that this is old code that was contributed by a 3rd party and it refers to the old push servers.

You need to write new code based on the current documentation which we provide in Java. You can contribute to that documentation effort in our wiki.

Read More

Wednesday, March 23, 2016

Registering Push IOS Notification with Telerik Appbuilder

1 comment

I have registered my Telerik Appbuilder (cordova) app for Push Notifications. Everything works fine, except for the fact that when the user is inside the application, he does not receive the push notification.

It works fine as long as he is on the 1 page that registers his push ie:

var registerPush = function (user, callback) {     $(".modal-loader").show();     document.addEventListener("deviceready", function () {         var el = new Everlive('m4yh8cw6ei7xxwio');          var pushSettings = {             iOS: {                 badge: true,                 sound: true,                 alert: true,                 clearBadge: true             },             notificationCallbackIOS: function (e) {                              navigator.notification.alert(e.alert, function () { }, "Alert", "Ok");             },             customParameters: {                 login: user             }          };          el.push.register(             pushSettings,             function () {                 $(".modal-loader").hide();                 callback();             }             ,             function errorCallback(error) {                 // This callback will be called any errors occurred during the device                 // registration process                 console.log("error registering push");                 console.log(data);             }         );     }, false); } 

If the user is on the page that actually registers this function, then he will be alerted via the navigationCallbackIOS. but as soon as we browse to a different page via:

 location.href= nextpage.html  

then the navigationCallbackIOS no longer works. What is the logic I need to implement here to have a global callback that works on every page?

2 Answers

Answers 1

If you change the page like this location.href= nextpage.html, then it's a different page, the webview is reloaded and all the code you executed on the index.html won't exist anymore.

You have two options.

  1. Switch to SPA, where you only have the index.html and you load just the contents of the nextpage.html, but don't navigate to it using the location.href
  2. Execute all the code on every .html file. If you have a pushHandler.js (example) where you init the push and register the listeners, link it on any .html so it is executed again when you change the page.

Answers 2

An AJAX request instead of a location.href change would be really better for three motivations: 1. Speed 2. No reload (don't need to reload every single resource everytime) 3. Global scope - in your case the push notification registration, don't need to be re-run every page change.

To do so you could create a element and then load into it the content of the other pages.. Take a look here for some proof of concept. It's basically all around managing an XMLHttpRequest and putting the result into a DOM element.

Read More

Friday, March 18, 2016

No-quota push notifications for Windows Phone company app

Leave a Comment

Is it still possible to enable authenticated (no-quota) push notifications for company app on Windows Phone?

There were a couple of blog posts by Windows Phone team documenting the process to enable no-quota push notifications for company app but now, on development portal, it is not possible to upload a certificate without linking it to an app.

I'm sure Microsoft added this feature a couple of years ago but now it seems to has been removed.

enter image description here

Do you know if authenticated push notifications for company app is still supported by Microsoft?

0 Answers

Read More