Silent Authentication in Actionscript without generating the dialog box - ios

I need to send the device token required for push notification in iOS to urban-airship server from the actionscript code. How can i do that? I am using their API's in my app. I am just using urban-airship to test push notifications on my app.
Since their url requires user authentication, I want to write code so that authentication happens silently without generating the pop dialog.

I finally figured out myself how to solve this problem:
// AIR developer can send the tokenId received in event.data to his server via URL request
var urlRequest:URLRequest;
var urlLoader:URLLoader = new URLLoader();
var tokenId:String; //tokenId received after registering for push notifications
var urlString:String = "https://go.urbanairship.com/api/device_tokens/" + tokenId;
urlRequest = new URLRequest(urlString);
urlRequest.authenticate = true;
urlRequest.method = URLRequestMethod.PUT;
URLRequestDefaults.setLoginCredentialsForHost("go.urbanairship.com",<userId>,<password>) ;
urlLoader.load(urlRequest);
urlLoader.addEventListener(IOErrorEvent.IO_ERROR, onError);
urlLoader.addEventListener(Event.COMPLETE, onComplete);
urlLoader.addEventListener(HTTPStatusEvent.HTTP_STATUS, onStatus);

Related

Twilio multiple push credential sid

I'm trying to implement Twilio swift quick start app, anyway I want to configure the app on both platforms iOS and Android,
I reached step 8 in the iOS tutorial
and I have a new PUSH_CREDENTIAL_SID for the iOS from the APN type, while the Android app is from the FCM type already have a PUSH_CREDENTIAL_SID that is being used in the config server file.
$ACCOUNT_SID = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
$API_KEY = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
$API_KEY_SECRET = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
$PUSH_CREDENTIAL_SID = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
$APP_SID = 'XXXXXXXXXXXXXXXXXXXXXXXXX';
How can I Add multiple PUSH_CREDENTIAL_SIDs for both apps ? or is there another way to figure this out ?
Thanks in advance
In your code you can have only 1 push_credential_sid.
In order to use the android AND ios at the same time, you should go into your project using this link: https://www.twilio.com/console/notify/services
Create a new service, and you will be able to create a service with the serviceID for android and IOS.
It will provide you a new serviceID to (SID) to use in your backend code.
And it should work for both platform :)
source : https://www.twilio.com/docs/notify/configure-ios-push-notifications#configure-your-twilio-service-to-use-your-apns-credentials
From the backend server, it only can config one push service id in 'PUSH_CREDENTIAL_SID', but if you check the backend code logic, then we can find it just use these information and create a JWT for the APP. So for the accessToken API, APP can pass one more parameter push_sid (the current parameter is identity), backend server will parse this push_sid from the APP request, but do not read from env config any more.
Android will pass the FCM push service id and iOS will pass the APN service id, so one server can support both Android and iOS.
You can control through IF/ELSE logic by passing DEVICE TYPE parameter.
public function createTwilioToken($deviceType = 'ANDROID')
{
$twilioAccountSid = config('app.TWILIO_ACCOUNT_SID');
$twilioApiKey = config('app.TWILIO_API_KEY_SID');
$twilioApiSecret = config('app.TWILIO_API_KEY_SECRET');
$conversationId = config('app.TWILIO_CONVERSATIONS_SERVICE_SID');
$androidPushCredentialSid = config('app.TWILIO_PUSH_ANDROID_CREDENTIAL_SID');
$iosPushCredentialSid = config('app.TWILIO_PUSH_IOS_CREDENTIAL_SID');
// choose a random username for the connecting user
$identity = 'USER-IDENTITY';
// Create access token, which we will serialize and send to the client
$token = new AccessToken(
$twilioAccountSid,
$twilioApiKey,
$twilioApiSecret,
86400,
$identity
);
// Create Chat grant
$grant = new ChatGrant();
$grant->setServiceSid($conversationId);
if ($deviceType == 'IOS')
{
$grant->setPushCredentialSid($iosPushCredentialSid);
}
else if ($deviceType == 'ANDROID')
{
$grant->setPushCredentialSid($androidPushCredentialSid);
}
// Add grant to token
$token->addGrant($grant);
return $token->toJWT();
}

Update device data on IoT for Automotive Starter Application using Bluemix iOS Client api

I have successfully configured a Bluemix backend vehicle monitoring app described in this tutorial:
http://www.ibm.com/developerworks/library/mo-connectedcar-app/index.html.
I have configured and ran the tester app successfully. I have also successfully initiated BMSClient on iOS( after adding mobile access service to the backend app), using the following code:
BMSClient.sharedInstance.initialize(bluemixAppRoute: backendURL, bluemixAppGUID: backendGUID, bluemixRegion: BMSClient.Region.usSouth)
let mcaAuthManager = MCAAuthorizationManager.sharedInstance
mcaAuthManager.initialize(tenantId: tenantId)
BMSClient.sharedInstance.authorizationManager = mcaAuthManager
BMSClient.sharedInstance.authorizationManager = MCAAuthorizationManager.sharedInstance
Here is a snippet of how tester app updates the information:
var id = $("#prop_id").val();
var property = $("#property").val();
var value = $("#value").val();
var payload = {
id: id,
property: property,
value: value
};
var group = id.split("-")[0];
var num = id.split("-")[1];
var message = new Messaging.Message(JSON.stringify(payload));
message.destinationName = "iot-2/type/"+window.config.iot_deviceType+"/id/"+id.split("-")[0]+"/cmd/setProperty/fmt/json";
$("#statusMessage").html("Published command!<br><b>Topic: </b>" + message.destinationName + "<br><b>Payload: </b><pre>" + JSON.stringify(payload, null, 4) + "</pre>");
$("#statusMessage").css("display", "block");
client.send(message);
Now I want to update manage(update properties, and/or send message to) the simulated vehicles via iOS app. The thing is that I am unable to find an API to do this on iOS.
Do I need to develop a backend API also? If no, on iOS, how can I get an API to do this?
Also here are URLs:
Backend app: http://alvi-app.mybluemix.net/
Tester app URL to update properties: http://alvi-app.mybluemix.net/tester
You will need to develop a custom backend API to accept messages for updating properties, etc. sent from your iOS app.
You can send a REST request using the BMS Core libraries from your iOS app to your backend. Then you can have your backend process these requests to update properties, etc.
https://github.com/ibm-bluemix-mobile-services/bms-clientsdk-swift-core
The Core SDK has an example of a REST request in the README.

Sending sms from iOS app using Plivo API swift

How do I use plivo SMS API in my iOS app using Swift. I read lot of documentation regarding this. I'm not sure how to implement it on swift.
var plivo = require('plivo');
var p = plivo.RestAPI({
authId: 'Your AUTH_ID',
authToken: 'Your AUTH_TOKEN'
});
var params = {
'src': '1111111111', // Sender's phone number with country code
'dst' : '2222222222', // Receiver's phone Number with country code
'text' : "Hi, text from Plivo", // Your SMS Text Message - English
//'text' : "こんにちは、元気ですか?", // Your SMS Text Message - Japanese
//'text' : "Ce est texte généré aléatoirement", // Your SMS Text Message - French
'url' : "http://example.com/report/", // The URL to which with the status of the message is sent
'method' : "GET" // The method used to call the url
};
// Prints the complete response
p.send_message(params, function (status, response) {
console.log('Status: ', status);
console.log('API Response:\n', response);
console.log('Message UUID:\n', response['message_uuid']);
console.log('Api ID:\n', response['api_id']);
});
The above code is in Node.js, I want it to write in swift, and also I'm not sure how to integrate plivo into iOS app. I'm developing an app where it should send a sms to admin whenever user requests an order. So I just want the outgoing message from Plivo to admin. Any suggestions is really helpfull.
Plivo Sales Engineer here. Our recommendation is to host a server to which your iOS app would make a request to send the SMS. Then your server can use a Plivo helper library to make the API request which would send the SMS. This way your AuthID and AuthToken are stored on your server (to which only you have complete access) and you don't expose your Plivo credentials in your iOS app.
If you make a direct request of the Plivo API from your iOS app, then users potentially could find and misuse your credentials.
tl;dr - don't put your authentication credentials in places other people can read it.
So without a helper library you will have to just make use of their REST API. From their site, sending an SMS can be done by POSTing your information to
https://api.plivo.com/v1/Account/{auth_id}/Message/
As for the Swift part take a look at NSMutableURLRequest or if you need help with the networking request you can look at Alamofire
If you want to use Rest API you can do like this:
lazy var plivoRestAPI: PlivoRest = {
let rest = PlivoRest(authId: Constants.Credentials.Plivo.AuthId,
andAuthToken: Constants.Credentials.Plivo.AuthToken)!
rest.delegate = self
return rest
}()
let params = ["to": phoneNumberToCall,
"from": "1111111111",
"answer_url": "",
"answer_method": "GET"]
plivoRestAPI.callOutbound(params)

Azure Notification Hub: notifications not showing up if sent to group

I have a trouble making notification hub to work.
If I send notification to tag that has only one registration associated with it, then everything's fine. Here's source:
var alert = "{\"aps\":{\"alert\":\"some message(targeted)\"},\"inAppMessage\": \"text\"}";
hub.SendAppleNativeNotificationAsync(alert,"mytag").ContinueWith(t => {
var outcome = t.Result;
Console.WriteLine(outcome);
});
But if I try to sent my notification to all users, like so:
var alert = "{\"aps\":{\"alert\":\"some message(all users)\"},\"inAppMessage\": \"text\"}";
hub.SendAppleNativeNotificationAsync(alert).ContinueWith(t => {
var outcome = t.Result;
Console.WriteLine(outcome);
});
then no one gets the notification. I checked monitor in Azure portal but there were no errors present.
Do you guys have some ideas?
Behavior you described is incorrect. There is one known issue which can potentially cause such kind of errors for Apple only:
If some registrations in the Notification Hub have invalid device token (it typically happens when application switches from test APNS to production or if some fake tokens were used during testing in emulator) then APNS terminates connection during the send and all notifications being sent after that using same connection are just ignored. Right now Notification Hub does not handle this situation correctly.
Way to fix - clean up "bad" registrations. If you are about developing/testing and it is not critical to lose the data - just remove all the registrations. If you have a lot of existing users then email me and we will try to find solution for your particular case.
I had same issue and I tried to set true EnableTestSend property, but no luck. Then I just removed the tags while send notifications. It worked like charm.
NotificationOutcome outcome = null;
var alert = "{\"aps\":{\"alert\":\"" + "From " + user + ": " + message + "\",\"sound\":\"default\"}}";
outcome = await Notifications.Instance.Hub.SendAppleNativeNotificationAsync(alert);

How to get key/value data from PushNotification in PhoneGap Build

I'm using the Push plugin in PhoneGap Build. I am able to send as well as receive push notifications to my device. I'm sending the notification + additional data (specifically which page to load) using the node-gcm library to registered devices. Here's the code on my node.js server:
var gcm = require('node-gcm');
var message = new gcm.Message();
//API Server Key
var sender = new gcm.Sender('GCM API SERVER/BROWSER KEY');
var registrationIds = [];
// Value the payload data to send...
message.addData('message','Hello from Portland, OR!');
message.addData('title','My Push Notification');
message.addData('msgcnt','3');
message.addData('soundname','beep.wav');
message.addDataWithKeyValue('pageid','1234566788'); //THIS IS THE ADDITIONAL DATA I'D
// ... ID LIKE TO SEND TO MY PHONEGAP BUILD APP AND INTERPRET
message.timeToLive = 3;// Duration in seconds to hold and retry to deliver the message in GCM before timing out. Default 4 weeks if not specified
// At least one reg id required
registrationIds.push('REGISTRATION ID');
/**
* Parameters: message-literal, registrationIds-array, No. of retries, callback-function
*/
sender.send(message, registrationIds, 4, function (result) {
console.log("hello" + result);
});
Now that I believe I have sent the additional page data, I'd like to know how I can GET the data from the notification itself inside of my PhoneGap build application.
I'm also using jquery mobile to manage the different html pages (which basically makes each page a separate div inside of one html document) and could use feedback on how to load the notified page with this in mind.
Any help would be greatly appreciated, thanks so much!
-- 24x7
You can get the value of key/pairs of notification in phonegap as follows:
The message text can be retrieved with: e.message
All other key/value pairs can be retrieved with: e.payload.key
For example if you want get the title of the notification(in above) then you will get it in "e.payload.title".
After getting the value you can put conditional statemnets depending upon the value to go to different pages/divs.

Resources