didReceiveRemoteNotification not getting invoked - objective-c

I am creating app in iOS/android. When a remote notification is received in the device, didReceiveRemoteNotification should get called. But it is not happening. My server side code for sending msg through APNS is as under:
$deviceToken = $obj_listener->ref_id;
// Put your private key's passphrase here:
$passphrase = 'blahblah';
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', '/var/www/mobileapp/TestAppCK.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp){
$this->log->debug("Failed to connect: $err $errstr" . PHP_EOL);
exit("Failed to connect: $err $errstr" . PHP_EOL);
}
$badge_count = $obj_listener->badge_count + 1;
// Create the payload body
$body['aps'] = array(
//'alert' => 'Message received',
'sound' => 'default',
'badge' => $badge_count,
'msg_id' => $this->msg_id,
//'user_key' => $obj_listener->ref_id,
'email' => $obj_listener->to_email_id
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
// Close the connection to the server
fclose($fp);
My objective-c side code is as under:
- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo{
//UIWebView *NewWebView = NULL;
NSLog(#"didReceiveRemoteNotification function");
return;
}
I have checked for the device token in the server side code. It is correct for the device.
Why is the above function not getting called. Thanks in advance.

If you don't register for notifications at your app start, they will never be received.
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:(UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge |UIRemoteNotificationTypeSound)];
Now, about your server side, I suggest you run your code in debug mode and see if Apple's gateway is being properly reached through SSL. A simple bad cert or lack of it can take you away days of work. Personal experience.

If Application is not in background you should use following code
//-------------- check notification when app is come to foreground after apllication get terminated ----------------//
UILocalNotification *localNotif =
[launchOptions objectForKey:UIApplicationLaunchOptionsRemoteNotificationKey];
if (localNotif) {
[self handleRemotNotification:[launchOptions valueForKey:#"UIApplicationLaunchOptionsRemoteNotificationKey"]]; // private method
}

Related

mautic - I want to add contact in mautic via api

I want to add contact in mautic via an API. Below I have the code, but it's not adding the contact in mautic.
I have installed mautic in localhost. Studied the API form in the mautic documentation and tried to do it for at least 2 days, but I am not getting any results on it.
<?php
// Bootup the Composer autoloader
include __DIR__ . '/vendor/autoload.php';
use Mautic\Auth\ApiAuth;
session_start();
$publicKey = '';
$secretKey = '';
$callback = '';
// ApiAuth->newAuth() will accept an array of Auth settings
$settings = array(
'baseUrl' => 'http://localhost/mautic', // Base URL of the Mautic instance
'version' => 'OAuth2', // Version of the OAuth can be OAuth2 or OAuth1a. OAuth2 is the default value.
'clientKey' => '1_1w6nrty8k9og0kow48w8w4kww8wco0wcgswoow80ogkoo0gsks', // Client/Consumer key from Mautic
'clientSecret' => 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c', // Client/Consumer secret key from Mautic
'callback' => 'http://localhost/mtest/process.php' // Redirect URI/Callback URI for this script
);
/*
// If you already have the access token, et al, pass them in as well to prevent the need for reauthorization
$settings['accessToken'] = $accessToken;
$settings['accessTokenSecret'] = $accessTokenSecret; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenExpires; //UNIX timestamp
$settings['refreshToken'] = $refreshToken;
*/
// Initiate the auth object
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
/*
if( $auth->getAccessTokenData() != null ) {
$accessTokenData = $auth->getAccessTokenData();
$settings['accessToken'] = $accessTokenData['access_token'];
$settings['accessTokenSecret'] = 'id6dow060fswcswgsgswgo4c88cw0kck4k4cc0wkg4gows08c'; //for OAuth1.0a
$settings['accessTokenExpires'] = $accessTokenData['expires']; //UNIX timestamp
$settings['refreshToken'] = $accessTokenData['refresh_token'];
}*/
// Initiate process for obtaining an access token; this will redirect the user to the $authorizationUrl and/or
// set the access_tokens when the user is redirected back after granting authorization
// If the access token is expired, and a refresh token is set above, then a new access token will be requested
try {
if ($auth->validateAccessToken()) {
// Obtain the access token returned; call accessTokenUpdated() to catch if the token was updated via a
// refresh token
// $accessTokenData will have the following keys:
// For OAuth1.0a: access_token, access_token_secret, expires
// For OAuth2: access_token, expires, token_type, refresh_token
if ($auth->accessTokenUpdated()) {
$accessTokenData = $auth->getAccessTokenData();
echo "<pre>";
print_r($accessTokenData);
echo "</pre>";
//store access token data however you want
}
}
} catch (Exception $e) {
// Do Error handling
}
use Mautic\MauticApi;
//use Mautic\Auth\ApiAuth;
// ...
$initAuth = new ApiAuth();
$auth = $initAuth->newAuth($settings);
$apiUrl = "http://localhost/mautic/api";
$api = new MauticApi();
$contactApi = $api->newApi("contacts", $auth, $apiUrl);
$data = array(
'firstname' => 'Jim',
'lastname' => 'Contact',
'email' => 'jim#his-site.com',
'ipAddress' => $_SERVER['REMOTE_ADDR']
);
$contact = $contactApi->create($data);
echo "<br/>contact created";
Any help will be appreciated.
use Curl\Curl;
$curl = new Curl();
$un = 'mayank';
$pw = 'mayank';
$hash = base64_encode($un.':'.$pw);
$curl->setHeader('Authorization','Basic '.$hash);
$res = $curl->post(
'http://mautic.local/api/contacts/new',
[
'firstname'=>'fn',
'lastname'=>'ln',
'email'=>'t1#test.com'
]
);
var_dump($res);
This is something very simple i tried and it worked for me, please try cleaning cache and enable logging, unless you provide us some error it's hard to point you in right direction. Please check for logs in app/logs directory as well as in /var/logs/apache2 directory.
In my experience sometimes after activating the API in the settings the API only starts working after clearing the cache.
Make sure you have activated the API in the settings
Clear the cache:
cd /path/to/mautic
rm -rf app/cache/*
Then try again
If this didn't work, try to use the BasicAuth example (You have to enable this I the settings again and add a new User to set the credentials)
I suspect that the OAuth flow might be disturbed by the local settings / SSL configuration.
these steps may be useful:
make sure API is enabled(yes I know it's might be obvious but still);
check the logs;
check the response body;
try to send it as simple json via Postman
it may be one of the following problems:
Cache;
You are not sending the key:value; of the required custom field;
you are mistaken with authentication;
Good luck :)

React Native Fetch Return Network Request Failed

I am developing a simple app using React Native. I am testing it on Genymotion Android Emulator. I have created local web server to listen to the requests, it is running at http://localhost:8082/API/.
I have tested the api and is working right. Then I make a fetch request from index.android.js.
here's the API sample request from the React Native code :
var api = { getUser(){
var url = "http://127.0.0.1:8082/API/";
return fetch(url)
.then((res) => res.json())
.catch(
(error)=>{
console.log('error' + error.message);
throw error;
}
);
}
}
module.exports = api;
here's the code from Api Server (built with flightPHP)
Flight::route('GET /',function(){
try{
$db = new PDO('mysql:host=localhost;port=3307;dbname=testapp', 'root','');
$stmt = $db->prepare("SELECT * FROM user LIMIT 1");
$stmt->execute();
header('Content-type: application/json');
echo json_encode($stmt->fetchAll(PDO::FETCH_ASSOC));
$db = null;
}catch(Pdoexception $e){
echo $e->getMessage();
}
});
after execute this call i receive Network Request Failed(). it seems android simulator not recognized the api url. any suggestion ? thanks before
i already solved. just change the API url var url = "http://127.0.0.1:8082/API/ in the React Code. to var url = "http://local-ip-address:8082/API/
to check your local ip just run ipconfig from command line / cmd
You can use ngrok to overwrite network requests.
Android is an emulator, and when you fetch 127.0.0.1, it goes to the local phone.
ngrok will create a link that is accessible from the web and redirect to the local web server.

Apple Push notification script not working

I am using this php script but its producing output Message successfully delivered but not sending notification. i have already check device id and certificates they are perfect and working fine with another script.
<?php
// Put your device token here (without spaces):
$deviceToken = 'fbf04bf4ace2f1e823016082da3a798cf3ab666ae99a395b65e364eb4c6d6d4a';
// Put your private key's passphrase here:
$passphrase = '123';
// Put your alert message here:
$message = 'A push notification has been sent!';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'key.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client('ssl://gateway.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT | STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array('alert' => array('body' => $message, 'action-loc-key' => 'Look', ), 'badge' => 2, 'sound' => 'oven.caf', );
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
echo "<pre>Result : ";
print_r($result);
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
?>
Can any one help me to getting out of this.?
Thanks in advance
I encounter similar problem when i first start iOS push notifications
There Will be possibility that you are doing a development push rather than a production push
Change the server to ssl://gateway.sandbox.push.apple.com:2195 and use your development push notification key to give a try.
That solves my problem
I think you have to change port number
You code: ssl://gateway.push.apple.com:2195. 2195 use for sandbox and 2196 use for live.
Can you please change it and try.
Hope this work.

Apple Push Notification from Server

I have followed :
Apple Push Notification Services Tutorial.
And it worked for me locally.
Next, i want to send push notifications from my server?
I have uploaded simplepush.php and ck.pem to my server. When i check http://www.myserver/simplepush.php it gives me error:
*Warning: stream_socket_client() [function.stream-socket-client]: unable to connect to ssl://gateway.sandbox.push.apple.com:2195
(Connection timed out) in /home/cherry/public_html/simplepush.php on
line 21 Failed to connect: 110 Connection timed out*
Could you please help me?
PHP Code:
<?php
// Put your device token here (without spaces):
$deviceToken = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx';
// Put your private key's passphrase here:
$passphrase = 'xxxxxxxxxx';
// Put your alert message here:
$message = 'My first push notification!';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
Is the PHP compiled with SSL? And is it the same version as your local version?
Or maybe the firewall of some kind blocks connection to 2195 port from your server?
Can you log in to this server (to a shell of some kind) and check if you can connect via telnet to this server and port:
$ telnet gateway.sandbox.push.apple.com 2195

Send Push Notifications to all users

So, I have an App. This app, send a Push Notification using this PHP code:
<?php
$deviceToken = '4bc9b8e71b9......235095a22d';
// Put your private key's passphrase here:
$passphrase = '12345';
// Put your alert message here:
$message = 'My Message Here!';
////////////////////////////////////////////////////////////////////////////////
$ctx = stream_context_create();
stream_context_set_option($ctx, 'ssl', 'local_cert', 'ck.pem');
stream_context_set_option($ctx, 'ssl', 'passphrase', $passphrase);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err,
$errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $deviceToken) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
echo 'Message not delivered' . PHP_EOL;
else
echo 'Message successfully delivered' . PHP_EOL;
// Close the connection to the server
fclose($fp);
My question is: If I have more than one users in my app, and I run this PHP code in Terminal, the Push Notification will be send only to this Device (4bc9b8e71b9...), or it'll be send to all of my users? If this will be sent only to this Device, how can I send the Push to all my users?
PS: I followed this tutorial, and it worked as well, except because i dont know if the Push will be send to all my users.
Sorry for the bad english, and thanks a lot!!
The usual approach is to store tokens in the database and once you need to send them - just select the tokens from the DB and loop through them.
the code might look like that
$pdo = new PDO(
"mysql:host=$db_host;port=$db_port;dbname=$db_name",
$db_user,
$db_pass
);
$pdo->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
$select_tokens_sql = 'SELECT * FROM tokens';
$select_tokens_statement = $pdo->prepare($select_tokens_sql);
// Open a connection to the APNS server
$fp = stream_socket_client(
'ssl://gateway.sandbox.push.apple.com:2195', $err, $errstr, 60, STREAM_CLIENT_CONNECT|STREAM_CLIENT_PERSISTENT, $ctx);
if (!$fp)
exit("Failed to connect: $err $errstr" . PHP_EOL);
echo 'Connected to APNS' . PHP_EOL;
// Create the payload body
$body['aps'] = array(
'alert' => $message,
'sound' => 'default'
);
// Encode the payload as JSON
$payload = json_encode($body);
$select_tokens_statement->execute();
$tokens = $select_tokens_statement->fetchAll();
//loop through the tokens
foreach($tokens as $token) {
// Build the binary notification
$msg = chr(0) . pack('n', 32) . pack('H*', $token) . pack('n', strlen($payload)) . $payload;
// Send it to the server
$result = fwrite($fp, $msg, strlen($msg));
if (!$result)
echo 'Message to the device ' . $token . ' not delivered' . PHP_EOL;
else
echo 'Message to the device ' . $token . ' successfully delivered' . PHP_EOL;
}
// Close the connection to the server
fclose($fp);
It might also be a good idea to listen to apple feedback service just after you have finished sending push notifications. It will tell you if on some devices your app is not present anymore so you can safely remove corresponding tokens from the database.
You'll have to loop over all of your device tokens and write them to the gateway with fwrite()