table of contents - pivotal · 2019-07-01 · push notification service for pivotal cloud foundry...
TRANSCRIPT
1249
1222252627272727282829292930303131313131323232344858596068717275778194
TableofContents
TableofContentsPushNotificationServiceforPivotalCloudFoundryInstallationDevOpsUsingtheDashboardV1.6.*PushNotificationsASGInstallationNetworkSetupGuideDevelopmentGuideFirstPushWalkthroughStep1Step2Step3Step4Step5Step6Step7Step8Step9Step10GeofenceWalkthroughStep1Step2Step3Step4Step5Step6Step7iOSPushClientSDKAndroidPushClientSDKWindowsPhone8.1PushClientSDKAPIsPushRegistrationRegistrationsTopicsCustomUserIDsScheduleGeofencesPushNotificationServiceReleaseNotes
©CopyrightPivotalSoftwareInc,2013-2018 1of98 1.6
Push Notification Service for Pivotal Cloud FoundryThisisdocumentationforthePushNotificationService forPivotalCloudFoundry (PCF).
ProductSnapshotCurrentPushNotificationServiceforPCFDetails
Version:v1.6.3Release Date:January2017SDK Versions:Androidv1.6.2,iOSv1.6.0Compatible Ops Manager Version(s):v1.7.8andlaterCompatible Elastic Runtime Version(s):v1.7.x,v1.8.xvSphere support?YesAWS support?YesGCP support?Yes
UpgradingtotheLatestVersion
PleaseupgradetoPushv1.4.5+beforeupgradingtoPCFv1.6.3.
ConsiderthefollowingcompatibilityinformationbeforeupgradingthePushNotificationServiceforPivotalCloudFoundry.
Ops Manager VersionSupported Upgrades from Imported Push InstallationFrom To
v1.3.x
v1.1.0 v1.1.1
v1.1.1 v1.2.0
v1.2.0 v1.2.1
v1.4.xv1.2.0 v1.2.1
v1.3.0 v1.3.1
v1.5.2+
v1.2.0 v1.2.1
v1.2.1 v1.3.0
v1.3.0 v1.3.1
v1.3.x v1.3.2–v1.3.5
v1.6.x v1.3.5 v1.4.5+
v1.7.8+ v1.4.5+ v1.6.3
v1.8.x v1.4.5+ v1.6.3
AboutThePivotalPushNotificationService forPivotalCloudFoundry allowsdeveloperstocreateamobilebackendthatcanbeusedtosendpushnotificationstomobileapps.TheserviceconnectsandmanagestheinterfacetoApplePushNotificationService,GoogleCloudMessaging,WindowsPushNotificationServices,andBlackBerryPushService.
EachmobileappcommunicateswiththeserviceforregistrationsandnotificationpreferencesbyusingthecorrespondingclientSDK.Back-endbusinesslogicserverssendpushnotificationstoallusers,usersbyplatform,usersbygeolocation,oruserswithspecifiedtagsbysendingtherequesttotheappropriatePushNotificationServiceAPIendpoint.
©CopyrightPivotalSoftwareInc,2013-2018 2of98 1.6
Forinstallation,aPCFadministratorinitiallyimportsthePivotalPushNotificationspackageintoPCFOperationsManagerandconfiguresitviatheDashboardatwhichpointtheservicebecomesavailabletosendnotifications.TheDashboardprovidestheabilitytoconfigureapps,environments,anddevice-specificserviceparameters.ClientSDKsforiOSandAndroidprovideasimplifiedwaytointegratewiththePushNotificationsservice.WindowsPhone8,Windows8,andBlackberry10appscanalsousetheservice.
ThePushNotificationsservicerequires:
PivotalRabbitMQ
Redisdatabase(PivotalRedisoruserprovided)
MySQLdatabase(PivotalMySQLoruserprovided)
©CopyrightPivotalSoftwareInc,2013-2018 3of98 1.6
InstallationThisdocumentdescribeshowtoinstallthePivotalCloudFoundry(PCF)PushNotificationService.
ThePCFPushNotificationServiceinstallsasasuiteoffiveCFappsdeployedinthe system orgunderthe push-notifications space.
API
Dashboard
ServiceBroker
Scheduler
Analytics
AdefaultinstallationdeploysfiveApplicationInstances(AIs),oneforeachappshowabove.Forproduction deployments,Pivotalrecommendsdeployingaminimumoftwoinstancesforeachpushapp,10AIstotal,perPCFenvironment.AdditionalAPIapplicationinstancesmayberequireddependingonthepeakloadrequired,withpeakloaddefinedasthemaximumnumberofnotificationssentpersecond.
DependenciesThePushNotificationservicedependsonMySQL(optionallyMySQLforPivotalCF ),RabbitMQforPivotalCF ,andRedisforPivotalCF beingsuccessfullyinstalledonPivotalCloudFoundry .
DownloadtheProductDownloadthePushNotificationsoftwarefromPivotalNetwork
AddingtheProductTogetstartedwithPush,youneedtoaddtheproduct withPivotalOpsManager.
Beforeyoucancompletetheinstallationyoumustprovidesomeconfiguration.
SetEncryptionKeyFromOpsManagerclickonthePivotalPushNotificationServicetileandgotothe“SecuritySettings”section.Generateanencryptionkeybyrunningthefollowingcommandinterminal(youshouldsetyourownpasswordhere):
opensslenc-aes-128-cbc-ksamplepassword-P-mdsha1
Thisproducesasalt,key,andinitializationvector.Copythekeyintothe“EncryptionKey”fieldonOpsManagerandclick“Save”.ThiskeyisusedforsymmetricencryptionofpushcertificatesandAPIkeys.
ConfigureMySQLFromOpsManagerclickonthePushNotificationServicetileandgotothe“MySQLSettings”section.SelectMySQLServicetouseMySQLforPCF .Seethe[Installation]sectionoftheMySQLforPCFdocumentation formoreinformation.
WhenusingtheMySQLforPCFserviceforPushNotifications,youmustprovideaMySQLforPCFserviceplanname.PivotalrecommendscreatingacustomMySQLforPCFserviceplancalled“Push”.YoucanfindinstructionsforcreatingacustomserviceplanintheMySQLforPCFServicePlansdocumentation.Afteryouidentifytheappropriateserviceplan,enteritsnameinthetextfield,suchas“Push”.
Touseanexternal(userprovided)MySQLserverselect“External”andfillintherequiredfields.
Afteryouhavecompletedthisconfiguration,click“Save”.
©CopyrightPivotalSoftwareInc,2013-2018 4of98 1.6
ConfigureRedisforAnalyticsandLogsFromOpsManagerclickonthePushNotificationServicetileandgotothe“AnalyticsRedisSettings”section.SelecttheRedisservicetousePivotalRedisservice .IfyouselectthisoptionyoumustinstallthePivotalRedisserviceaswell.Selectfromthedrop-downthetypeofserviceplantouse.SeemoreinformationaboutthePivotalRedisservice
Touseanexternal(userprovided)Redisserverselect“External”andfillintherequiredfields.-NOTE:ThisreleasedoesnotsupportRedisCluster ifyouareusingexternalredis.-Ifyouareusingredisbehindatcpproxy,makesuretouseSessionPersistence.
Thesamestepsapplytosetthe“LogsRedisSettings”sectionasabove.
Afteryouhavecompletedtheseconfigurationsclick“Save”.
DefaultErrandBehaviorAsofv1.10,OpsManagerskipsallunnecessaryBOSHerrandswhenperformingupdatestoPCFservices.Formoreinformationaboutthisbehavior,seetheOpsManagerdocumentation,ManagingErrandsinOpsManager .
ForPCFPushNotificationservices,PivotalstronglyrecommendsthatoperatorssetthedefaultErrandexecutionbehaviortoOn,throughtheErrandsForminthePushNotificationstilesettingsinOpsManager.
UploadStemcellOpsManagerversionsgreaterthanv1.5requirethatyouuploadthestemcellthatthePushNotificationServiceuses.YoucanacquirethisstemcellfromtheBoshStemcellDirectory .Afteryouhavethestemcell,uploadittoOpsManagerviathe“Stemcell”tabinthePushNotificationServicesconfigurationpage.
ApplyChanges
©CopyrightPivotalSoftwareInc,2013-2018 5of98 1.6
AfterthesecuritysettingsandMySQLconfigurationarecompleteyoucanclick“InstallationDashboard”toreturntotheOpsManagerdashboardandthenclick“ApplyChanges”tocompletetheinstallation.
CreatingaTenantSincev1.4,thePCFPushNotificationServicesupportsmultipletenants.EachtenantinthePCFPushNotificationServicecanhaveitsownsetofapplications.Inordertosetupanewtenant,youneedtocreateanewspaceinyourPCFAppsManager.Youcanuseanyorgthatisappropriateforyourneeds.
TheapplicationsforthePushNotificationServiceitselfareinthe“push-notifications”spaceinthe“system”org.Don’tusethisspaceforyourowntenant.Createanewspaceinstead.
AfteryouhaveselectedyourspaceyoucancreateyourPushserviceinstancebyclickingthe“AddService”button.Selectthe“PCFPushNotificationService”servicefromtheMarketplace.Selectthedefault(free)plan.Givetheserviceanameandaddittoyourspace.
OnlycreateoneinstanceofthePushNotificationServiceperspace.
Aftertheserviceinstanceiscreatedyoucanclickthe“Manage”linkontheserviceinstancetoshowtheDashboardforthePushNotificationService.
YoucancontrolaccesstothePushDashboardbyusingtheusingCloudController.AnyuserswithaccesstoseethespacealsohaveaccesstousethePushNotificationDashboard.YouneedtobeloggedintotheAppsManagerbeforeyoucanaccessthePushDashboard.
DashboardsetupAftertheservicehasbeenadded,verifythesuccessfulinstallationbyviewingthedashboard.
Note:
ThePushNotificationserviceisaCFServicethatisinstalledinthe“System”organd“push-notifications”space.YouseeitintheMarketplace.EachinstanceofthePushNotificationsServicehasitsowndashboardURL.
Loginas“admin”totheCFconsoleandgotothatorgandspace.ToaccessthePushDashboard,clickonthe“Manage”linkforthe“push-service-instance”service.
InstallationVerificationTherearetwodifferentwaystomanuallyverifytheinstallationwassuccessful.
ThefirstwayistousetheCFCLI toviewtheinstalledappsandservices.InstructionstologinareincludedontheCFCLIpage.
Theorganizationis“System”andthespaceis“push-notifications”,bothareneededtoviewtheappsandservicesusingtheCFCLI.
AftersettingtheapiandloggingintotheCFCLI,typein cfa toseealistingofalltheappscurrentlyunderthepush-notificationsspace,withaquickoverviewoftheircurrentstatus.
Theappsthatshouldappearareasfollows:
Dashboard(push)
Backend(push-api)
Scheduler(push-scheduler)
Analytics(push-analytics)
©CopyrightPivotalSoftwareInc,2013-2018 6of98 1.6
ServiceBroker(push-service-broker)
Andtheyshouldallhavetheirownuniqueurls.
Fortheservices,typingin cfs givesalistoftheservicesplustheappswhichtheyareboundto.
Theservicesthatshouldappearareasfollows:
MySQL(push-notifications-mysql)
RabbitMQ(push-notifications-rabbitmq)
RedisforAnalytics(push-notifications-analytics-redis)
RedisforLogs(push-notifications-logs-redis)
PushServiceBroker(push-service-broker)
Thesecondwayistousethedeveloperconsole.Afterloggingin,selecttheSystemorganizationfromthedropdownbox.Selectingtheorganizationshowsallofthespaceswhicharenestedwithin.
Clickonthepush-notificationsspace,whichshowtheappsandservicesrunningunderthatspace.
©CopyrightPivotalSoftwareInc,2013-2018 7of98 1.6
Thelistingofapplicationsshowthestatus,thename,theurltoaccesstheapp,howmanyinstancesofthatappisrunning,andhowmuchmemorythatappisusing.Verifythateachappsstatusis100%,whichmeansitisrunningasexpected.
Thelistingofservicesshowthename,theplan,andhowmanyappsareboundtoit.Someserviceshaveextraoptions,suchasmanagingtheservice,orlookingupdocumentationontheservice.
NotesThereisnoautomatedupgradepathfromv1.2.xtov1.3.0.Stepsareavailabletobackupandrestoredatabetweentheseversions.
Forv1.0-v1.2,thedefaultlocationforthedashboard http://push-notifications-dashboard.cf.example.com
Forv1.0-v1.1,thedefaultinstallationinstallstheapplicationstothe“Pivotal”organd“push-notifications”space.
©CopyrightPivotalSoftwareInc,2013-2018 8of98 1.6
DevOps
UninstallingIMPORTANT
Pushisastatefulservice!
ItisadvisedthatyoudoNOT UNINSTALLthePushtileinordertosolveproblemswithbindingorcommunicatingwithotherservices.ThePushteamwillprovideinstructionsonhowtomanuallyrestoretheseconnections.
DeletingthetilewillcauseallofthePushuserdatastoredintheMySQL,Redis,andRabbitMQservicestobeDELETEDaswell.
IfyouneedtodeletethePushtileordeleteanyofitsconnectionstotheaboveservicesthenyouwillneedtoBACKUPandRESTOREallofthePushuserdataintheseservices.
Instructionsforbackingupandrestoretheuserdataisprovidedbelow.
TroubleshootingCommonProblemsForsolutionstocommonproblems,pleaseseeourtroubleshootingguide.
ConfigurableEnvironmentVariables
PushApi
push_security_trustAllCerts(Boolean,default:inheritedfromcfruntime)
Whenthe push_security_trustAllCerts environmentvariableissetto true thePushAPIwillskipSSLvalidationoncallstoRabbitMQandthePushScheduler.Thisvariableisnecessaryinenvironmentsthatuseself-signedcertificates.Thedefaultvalueis false unlesstheCFRuntimeisconfiguredtotrustself-signedcertificates.
push_scheduler_sendImmediatelyWithin(Integer,default:60)
The push_scheduler_sendImmediatelyWithin environmentvariablepertainstoscheduledpushnotifications.Itisathreshold(inseconds)withinwhichthepushserverwillskipschedulingapushandsimplysenditrightaway.Thedefaultvalueis60seconds.Ifapushisscheduledwithin60secondsofthecurrenttimeitwillnotbescheduledbutsimplybesentrightaway.Youcanmodifythatthresholdbymodifyingthisenvironmentvariable.
push_apns_sendReceipt(Boolean,default:true)
The push_apns_sendReceipt environmentvariableisaflagthatenablespassingareceipttothedeviceaspartofthepushpayload.Thereceiptisauniqueidforeachmessagethatcanbeusedforanalytics.ThisflagenablessendingreceiptsforiOS/APNS.
push_apns_logDeviceTokens(Boolean,default:true)
The push_apns_logDeviceTokens environmentvariablecontrolsthelogverbosityoftheAPNSpushhandler.Whensetto true thedevicetokenforeveryrecipientofapushwillbeloggedasthepushissent.Notethatthisextraloggingwillreducepushthroughput.
push_gcm_sendReceipt(Boolean,default:true)
The push_gcm_sendReceipt environmentvariableisaflagthatenablespassingareceipttothedeviceaspartofthepushpayload.Thereceiptisauniqueidforeachmessagethatcanbeusedforanalytics.ThisenablessendingreceiptsforAndroid/GCM.
©CopyrightPivotalSoftwareInc,2013-2018 9of98 1.6
push_gcm_logDeviceTokens(Boolean,default:true)
The push_gcm_logDeviceTokens environmentvariablecontrolsthelogverbosityoftheAndroidpushhandler.Whensetto true thedevicetokenforeveryrecipientofapushwillbeloggedasthepushissent.Notethatthisextraloggingwillreducepushthroughput.
Installingthepushserverbehindaproxy(availableinv1.3.2+)
StartinginPushversion1.3.2youcanroutecommunicationwithpushproviders(APNS,GoogleCloudMessaging)throughaproxyserver.GCMpushescanuseeitheraHTTPorsocksproxy.APNSpushescanonlyuseasocksproxy.Usethefollowingenvironmentvariablestospecifyproxies.
push_gcm_httpProxyHost(String,default:[empty])push_gcm_httpProxyPort(Integer,default:[empty])
The push_gcm_httpProxyHost and push_gcm_httpProxyPort environmentvariablesallowyoutospecifyanHTTPproxyserverthroughwhichtorouteGoogleAPIrequests(forAndroidpushes).
push_gcm_socksProxyHost(String,default:[empty])push_gcm_socksProxyPort(String,default:[empty])
The push_gcm_socksProxyHost and push_gcm_socksProxyPort environmentvariablesallowyoutospecifyaSOCKSproxythroughwhichtorouteGoogleAPIrequests.
Note:IfbothHTTPandSOCKSproxiesaredefinedforGCM,SOCKSwillbeused.
push_apns_socksProxyHost(String,default:[empty])push_apns_socksProxyPort(String,default:[empty])
The push_apns_socksProxyHost and push_apns_socksProxyPort environmentvariablesallowyoutospecifyaSOCKSproxythroughwhichtorouteAPNSpushrequests.
BackupAndRestore
BackupMySQLdataItishighlyrecommendedthatyouenableautomaticbackups withyourMySQLTile(RequiresanAmazons3Bucket).Additionally,youshouldalwaysbackupyourMySQLtileifyouareplanningonremovingPushNotificationServiceorMySQL.Youcanperformamanualbackupbyfollowingthedirectionsfoundhere:MySQLManualBackup
Followtheseinstructionstobackup thePushNotificationdatabase.
IntheAppsManagerconsoleinthe“system”orggotothe“push-notifications”spaceandthe“push-analytics”app.
Gotothe“Services”tab.
Click“▸Showcredentials”fortheMySQLservice.
Get“username”,“password”and“databasename”.
SSHintotheproxyforyourPivotalCFenvironment.
Fromtheproxyrun(usingthecredentialsabove):
mysqldump-hhostname-p-uusernamedatabase_name>push_db.sql
BackupencryptionkeyIntheAppsManagerconsolegotothe“push-api”appandgotothe“EnvVariables”tab.
Getandrecordthevaluefor crypto_applicationKey .Youwillneedthiskeyduringtheinstallation.
The crypto_applicationKey environmentvariablecontainsthekeywhichwillbeusedtoencryptsensitiveinformationusedbythepushserver
©CopyrightPivotalSoftwareInc,2013-2018 10of98 1.6
(i.e.:iOSpushcertificates,GoogleAPIkeys).Thisvalueissetatinstalltimeand .Youwillhoweverneedtorecordthisvalueinordersaveandrestorethepushnotificationservicedatabase.
RestoreMySQLdataFromtheAppsManagerconsoleinthe“pushnotifications”spacethroughthe“system”org,stopthe“push”and“push-api”applications.
Goto“Services”.
Click“▸Showcredentials”forMySQL.
Get“username”,“password”and“databasename”.
SSHintotheproxyforyourPivotalCFenvironment.
DeletedatafromPushinstallation(thisshouldjustbeemptydata)byrunningthefollowingcommandfromtheproxy(usingtheabovecredentials):
mysql-hhostname-p-uusernamename-e"dropdatabasedatabase_name;createdatabasedatabase_name;"
Importdatafromoldinstallbyrunningthefollowingcommandfromtheproxy(usingtheabovecredentials):
mysql-hhostname-p-uusernamedatabase_name<push_db.sql
Enablemigrations:
IntheAppsManagerconsole,findthe“push-api”applicationandgotothe“EnvVariables”tab.Edit liquibase_runMitgations andsetitto true .
Startthe“push-api”and“push”applications.
Disablemigrations:
IntheAppsManagerconsole,findthe“push-api”applicationandgotothe“EnvVariables”tab.Edit liquibase_runMigrations andsetitto'false’.
Restartthe“push-api”and“push”applications.
BackupRedisDataSeeredisbackupinstructions
©CopyrightPivotalSoftwareInc,2013-2018 11of98 1.6
Using the Dashboard V1.6.*
DashboardguideforotherversionsVersionList
ApplicationsAnapplicationinthePushDashboardrepresentsamobileapplicationfromtheperspectiveoftheapplicationauthor,includingallsupportedplatforms.Applicationsarelistedinthedropdownatthetopofthesidebar.
AddinganapplicationClickon CreateNew
Applicationinleftsidebar.Fillintheformandclick Save tocreatetheapplicationoroptionallyclick‘AddPlatform’toaddaplatform
fortheapplication.
EditinganapplicationClickonthe Configuration linkinthesidebarmenutobringuptheinformationabouttheapplication.Clickonthepenciliconunderthe Actions columntoedittheapplication.Editthefieldsandclick Save toupdatetheapplication.TheUUIDisimmutable.
RegeneratinganAPIkey
©CopyrightPivotalSoftwareInc,2013-2018 12of98 1.6
Clickonthe RegenerateAPIKey button.AnewAPIkeywillbegenerated.NOTE:youwillnolongerbeabletosendpushesusingthepreviousAPIkey.
DeletinganapplicationTodeleteanapplication,clickonthe Configuration linkinthesidebarmenutobringupinformationabouttheapplication.Clickonthedeleteiconunderthe Actions columntodeletetheapplication.NOTE:Thisiconwillbedisablediftheapplicationhasoneormoreplatforms.
PlatformsAplatformconfiguresplatformspecificattributestosendpushmessages.Forexample,thiswouldincludeacertificatenecessarytosendmessagestoApple’sAPNS,oratokennecessarytosendmessagestoGoogle’sGCN.Aplatformhasmanydevices.
Addingaplatform
©CopyrightPivotalSoftwareInc,2013-2018 13of98 1.6
OntheConfigurationpage,clickonthe AddNewPlatform
button.Fillintheformandclick Save tocreatetheplatform.
EditingaplatformOntheConfigurationpage,clickonthepenciliconlinknexttotheplatformyouwanttoedit.Editthefieldsandclick Save toupdatetheplatform.TheTypefieldcannotbechangedonceset.
©CopyrightPivotalSoftwareInc,2013-2018 14of98 1.6
DeletingaplatformOntheConfigurationpage,clickonthetrashiconlinknexttotheplatformyouwanttodelete.NOTE:Youcannotdeleteaplatformthathasdevices.Inordertoremovedevicesyoumustunregisterfromthedevice.
DevicesAdeviceisgivenauniqueidentifierwhichrepresentsauseroptingintoreceivepushnotifications.Thisidentifierisnotnecessarilyuniquetoadevicesinceitmightchangeiftheuserreinstallsthemobileapplication,orunsubscribesandresubscribes.
©CopyrightPivotalSoftwareInc,2013-2018 15of98 1.6
SendatestpushnotificationtoadeviceClickon'Devices’inthesidebarmenu.Clickonthe Test
Pushbuttonnexttothedevice.Filloutthepushform.See“Sendingapushmessage”fordetails
ontheformfields.
SendingaPushMessage
©CopyrightPivotalSoftwareInc,2013-2018 16of98 1.6
Clickon PushNotifications inthesidebarmenu,andclickthebutton CreatePushNotification
.
OntheCreatePushMessagepage,fillintheformandclick SendPushNotification
.
PushMessage:Thealertbodyforthemessage
TargetPlatform:Sendthepushtoalldevicesbelongingtoaspecificplatform(eg.iOS,Android,etc)
Tag(s):Sendthepushtoalldevicessubscribedtooneormoretags
Schedule
Send:Schedulethepushtobesentimmediatelyoratalatertime.Defaultsto“Immediately”Expire:Preventdeliveryofthemessageafteraspecifiedtime,ifdeliveryisdelayedforsomereason(eg.noconnectivityonuserdevice).Defaultis“Never”
InteractivePushCategory
iOS Only-Setthecategoryforapush(requiredforinteractivepushes)
ONLYSENDTOINTERACTIVEPUSHDEVICES:Filtertargetteddevicesforonlydevicesthatsupportinteractivepush
TargetLocation:Pickalocationtosetupageofence
TriggerType:Ifalocationisselected,triggertypedetermineswhenageofenceisactivated
A Note About Targeting
TargetPlatform
willtargetalldevicesoftheselectedplatform.Addingtagstothe Tag(s) fieldwillrefinethetargetlistdown,addingonlythosedevices
subscribedtooneofthelistedtags.
A Note About Sending Push With Invalid Certificate
©CopyrightPivotalSoftwareInc,2013-2018 17of98 1.6
iOS OnlySendingapushtoadeviceusinganinvalid .p12 certificatesetupinthedevice’scorrespondingplatformresultsinthedevicegettingremovedfromtheplatform.
TagsAtagallowspushnotificationstobesenttoalldevicesthathaveexplicitlysubscribedtoitasopposedtoallusersthathavetheapplicationinstalled.Thisallowsanapplicationtosendtargetedpushnotificationstoasubsetofdevices.Devicescansubscribetotagsviatheregistrationsapi.AvailabletagsarelistedinthetargettingsectionoftheCreateNotificationform.
LocationsLocationsallowyoutosendpushnotificationstoasubsetofuserswhoarewithin(orenter)theradiusofaspecifiedarea.
AddingaLocationGroupClick Locations ontheleftsidebarandthenclickthe AddLocation button.
©CopyrightPivotalSoftwareInc,2013-2018 18of98 1.6
FillintheNameofthelocation.YoumaytypeinaLatitudeandLongitudepair,orsimplyclickonthemap.Selectaradiusthatsuitsthelocation.Onceallthedetailsareset,clickthe Create button.
AddingaLocationGroupClickonthe LocationGroup tab,andthenonthe AddLocationGroup button.
FillintheNameandDescriptionoftheLocationGroup.IntheTargetLocationfield,selectalocationfromthedrop-downorclickononeofthemarkersonthemap.Onceallthedetailsareset,clickthe Create button.
©CopyrightPivotalSoftwareInc,2013-2018 19of98 1.6
GeofencePushNotificationsFillinthedetailsofthePushNotification,suchasMessage,Platform,andSchedule.Selectfromthe TargetLocation drop-downeitheraLocationoraLocationGroup.TriggerTypefieldwillappearupontheadditionofLocation/LocationGroup.SelecteitherEnterorExit,dependingonhowyouwanttheGeofencetoactivate.Onceallthedetailsareset,clickthe SendPush
Notificationbutton.
©CopyrightPivotalSoftwareInc,2013-2018 20of98 1.6
LogsTheLogspagedisplaysanyloggedeventsthatoccurwhiletheLogspageisopen.Clickingthe“DownloadLogs”buttonwillcopythelogsdisplayedintoatextfileontoyourlocalmachine.
©CopyrightPivotalSoftwareInc,2013-2018 21of98 1.6
Push Notifications ASG Installation
ApplicationSecurityGroupsToallowthisservicetohavenetworkaccessyouwillneedtocreateApplicationSecurityGroups (ASGs).
Pre-InstallationRequirementsPushNotificationServicedependsonMySQL,RabbitMQ,andRedis.PleaserefertotheircorrespondingASGdocumentationtoensuretheirrequiredASGsareinplace.
PushServiceNetworkConnectionsThisserviceisdeployedasasuiteofapplicationstothe push-notifications spaceinthe system org,andrequiresthefollowingoutboundnetworkconnections:
Destination Ports Protocol Reason
17.0.0.0/85223,2195,2196
tcp ThisisApple’sIPaddresswhichisusedtoaccessAPNS
GOOGLE_IP_RANGE5228,5229,5230,443
tcp ThisisGoogle’surlforsendingGCMMessages
LOAD_BALANCER_IP 80,443 tcp ThisservicewillaccesstheloadbalancerandCAPI
ASSIGNED_NETWORK3306,5672,6379
tcpThisservicerequiresaccesstop-mysql,p-rabbitmq,p-redis,orexternalservices.ASSIGNED_NETWORK istheCIDRofthenetworkassignedtothisservice.
APNSAppleexposestheentire17.0.0.0/8blockandusesports2195,2196,and5223.Createafileapns.jsonasfollows:
[{"protocol":"tcp","destination":"17.0.0.0/8","ports":"2195,2196,5223"}]
Createasecuritygroupcalledapns: cfcreate-security-groupapnsapns.json
GCMGoogleunfortunatelyhasaverylargerangeofIPaddressesthatitcanuseforGCM.
Createafilegcm.jsonasfollows:
Note:WithoutApplicationSecurityGroupstheservicewillnotbeusable.
Note:Google’sASNis15169.Youcansearchfor“ASN15169”tofindthemostuptodatelistoftheirIPaddresses.
©CopyrightPivotalSoftwareInc,2013-2018 22of98 1.6
[{"protocol":"tcp","destination":"8.8.4.0/24","ports":"5228,5229,5230,443"},{"protocol":"tcp","destination":"8.8.8.0/24","ports":"5228,5229,5230,443"},
...restofGoogleIPselided...]
Createasecuritygroupcalledgcm: cfcreate-security-groupgcmgcm.json
LoadBalancerIfthebuilt-inHAProxyisbeingusedastheloadbalancer.TheIPaddressescanbefoundinPivotalElasticRuntimeTile→SettingsTab→NetworkingunderHAProxyIPs,(e.g.,10.68.196.250).Createafileload-balancer-https.jsonasfollows:
[{"protocol":"tcp","destination":"10.68.196.250","ports":"80,443"}]
Createasecuritygroupcalledload-balancer-https: cfcreate-security-groupload-balancer-httpsload-balancer-https.json
AssignedNetwork
LogintoOpsManagerandclickonthePivotalElasticRuntimeTile→SettingsTab→AZandNetworkAssignments.Notethenameofthenetworkselectedinthedrop-down(e.g.,“first-network”).ThenclickontheOpsManagerDirectortile→SettingsTab→CreateNetworks→“first-network”andnotetheCIDRinthesubnetssection(e.g.,10.68.0.0/20).Thisshouldallowthespacetoaccess p-mysql , p-rabbitmq ,and p-redis Thencreateafileassigned-network.jsonasfollows:
[{"protocol":"tcp","destination":"10.68.0.0/20","ports":"3306,5672,6379"}]
Createasecuritygroupcalledassigned-network: cfcreate-security-groupassigned-networkassigned-network.json
Pre-installationASGbindingLoginasanadministratorandcreatetheaboveASGs.Afterwards,createthespace push-notifications inthe system organdbindeachofthemtotheit:
cftarget-osystemcfcreate-spacepush-notificationscfbind-security-groupapnssystempush-notificationscfbind-security-groupgcmsystempush-notificationscfbind-security-groupload-balancer-httpssystempush-notificationscfbind-security-groupassigned-networksystempush-notifications
Note:Ifyoudecidetouseexternalservices,theIPaddresses,ports,andprotocolswillbedependentonwhatyouuse.
©CopyrightPivotalSoftwareInc,2013-2018 23of98 1.6
©CopyrightPivotalSoftwareInc,2013-2018 24of98 1.6
Network Setup Guide
APNS/iOSPush
ServerandDeviceSettingsThepush-apibackendneedstohavepersistentsocketsopentotheAppleAPNsservers.
InformationfromtheAppleSupportsite
TouseApplePushNotificationservice(APNs)youneedadirectandpersistentconnectiontoApple’sservers.YourdeviceconnectstoAPNsusingcellulardataifit’savailable.Ifthere’snoviablecellularconnectionthedeviceswitchestoWi-Fi.
IfyouuseWi-FibehindafirewalloraprivateAccessPointName(APN)forcellulardatathenyou’llneedadirectunproxiedconnectiontotheAPNsserversontheseports:
TCPport5223:ForcommunicatingwithApplePushNotificationservices(APNs).
TCPport2195:ForsendingnotificationstoAPNs.
TCPport2196:FortheAPNsfeedbackservice.
TCPport443:ForafallbackonWi-Fionlywhendevicescan’treachAPNsonport5223.
TheAPNsserversuseloadbalancingsoyourdeviceswon’talwaysconnecttothesamepublicIPaddressfornotifications.It’sbesttoallowaccesstotheseportsontheentire17.0.0.0/8addressblockwhichisassignedtoApple.
GCM/AndroidPush
ServerandDeviceSettingsThepush-apibackendneedstosendrequeststo“https://gcm-http.googleapis.com/gcm/send ”(port443).
DeviceswillneeddirectunproxiedconnectionstoGoogleserversonport5228.Android4.3anduphavefallbackcapabilitiestouseport443.
©CopyrightPivotalSoftwareInc,2013-2018 25of98 1.6
Development GuideFirstPushWalkthrough
FirstGeofenceWalkthrough
iOS
SampleApp
Android
SampleApp
WindowsPhone8.1
SampleApp
©CopyrightPivotalSoftwareInc,2013-2018 26of98 1.6
First Push WalkthroughStep1IntheCloudFoundryAppManager,clickonthe“Marketplace”link.Select“PushNotificationService”fromthelistofavailableservices.
Step2Selectthe“Default”serviceplan.GivetheserviceinstanceanameandmakesuretoselectthecorrectSpacefortheservicetobecreatedinbeforeclickingthe“Add”button.
Step3Youcannowclickonthe“Manage”linkforthePushNotificationsServiceinstanceyou’vecreated.ThiswillopenthePushDashboard.
©CopyrightPivotalSoftwareInc,2013-2018 27of98 1.6
Addanapplicationbyfillingintheformthatappearswhenfirstnavigatingtothedashboard.Ifapplicationsalreadyexist,youcanaccesstheaddapplicationscreenbyclickingon“CreateNewApplication”onthelefthandsidebardropdown.
Step4Fillinfieldsonthenewapplicationscreen.Therearetwofields:nameanddescription.Thesefieldsarepurelyforkeepingtrackofwhichapplicationiswhich.
Step5Createanewplatformbyclickingonthe‘AddPlatform’buttonandfillingouttheproperfieldsdependingontheplatformtype.
ForAndroidplatformsyouwillneedtoprovideProject NumberandGoogle Keyvalues.TheProject NumberisthenumericvaluefoundatthetopmiddleofaprojectontheGoogleDevelopersConsole .Donotusethe'ProjectID’.TheGoogle KeyisaServerAPIkey,createdonthe“Credentials”
©CopyrightPivotalSoftwareInc,2013-2018 28of98 1.6
screenoftheGoogleDevelopersConsole.
ForiOSplatformsyouwillneedtocreateaAPNS Development CertificateandAPNS Production CertificateusingtheAppleDeveloperWebsite .Thesefiles,alongwiththeirassociatedprivatekeys,needtobeexportedfromyourKeychain AccessprogramintoapasswordprotectedP12file.YouwilluploadthisP12fileandprovideitspasswordwhenyoucreateyourplatformonthePCFPushNotificationServicedashboard.
Step6Aftersaving,clickon'Configuration’ontheleftsidebar,thisiswheretheUUIDandsecretwillbefound.Thesevaluesareusedtoregisterdevicesandeventuallysendpushes.
Step7Nowyouwillhavetointegratethesdkwithyourapp.SeethegettingstartedsectionoftheSDKdocumentation.
Step8Clickonthe'Devices’linkontheleftsidebartoseeregistereddevices,andclickonthe'TestPush’buttonforthedeviceyouwishtosendapush.
©CopyrightPivotalSoftwareInc,2013-2018 29of98 1.6
Step9Fillinamessageandpresssendtosendatestmessage.
Step10Iftheserveracceptsthispushfordelivery,areceiptwillbeshownonscreen.Thisdoesnotguaranteedeliverytothedevice(devicecouldbeoff,notificationscouldbedisabled,etc).
©CopyrightPivotalSoftwareInc,2013-2018 30of98 1.6
Geofence WalkthroughModernmobiledevicescantracknumerousgeofences,eachofwhicharedefinedbyalat/longpairandaradius.Wheneverthedeviceentersorexitstheboundriesofageofence,anotificationcanbetriggered.ThetriggeringofanotificationisnotdependantonthedevicehavinganInternet/Dataconnection.
Step1CompletethestepsfromtheFirstPushWalkthroughguide.(Setupanapplication,platform(s)anddevices).
Step2Click Locations ontheleftsidebarandthenclickthe AddLocation button.
Step3FillintheNameofthelocation.YoumaytypeinaLatitudeandLongitudepair,orsimplyclickonthemap.Selectaradiusthatsuitsthelocation.Onceallthedetailsareset,clickthe Create button.
Createafewmorelocations.
Step4Clickonthe LocationGroup tab,andthenonthe AddLocationGroup button.
©CopyrightPivotalSoftwareInc,2013-2018 31of98 1.6
Step5FillintheNameandDescriptionoftheLocationGroup.IntheTargetLocationfield,selectalocationfromthedrop-downorclickononeofthemarkersonthemap.Onceallthedetailsareset,clickthe Create button.
Step6Clickon PushNotifications ontheleftsidebar,andthenonthe CreatePush
Notificationbutton.
Step7FillinthedetailsofthePushNotification,suchasMessage,Platform,andSchedule.Selectfromthe TargetLocation drop-downeitheraLocationoraLocationGroup.TriggerTypefieldwillappearupontheadditionofLocation/LocationGroup.SelecteitherEnterorExit,dependingonhowyouwanttheGeofencetoactivate.Onceallthedetailsareset,clickthe SendPush
Notificationbutton.
©CopyrightPivotalSoftwareInc,2013-2018 32of98 1.6
©CopyrightPivotalSoftwareInc,2013-2018 33of98 1.6
iOS Push Client SDK
SampleAppsYoucanfindthenewestversionoftheiOSSampleAppongithub
VersionThisdocumentcoversthePivotalCloudFoundryPushNotificationServiceiOSPushClientSDKv1.6.0.
Olddocumentation:
Version1.4.0
Version1.3.3
Version1.3.2
Version1.3.1
Version1.3.0
Version1.0.4
PleasenotethattherewasnoreleaseofthePushiOSSDKfor1.5.0.
FeaturesThePCFPushNotificationService PushClientSDKisalight-weightlibrarythatwillhelpyourapplicationregisterwiththePCFMobileServicesPushNotificationsservice.
TheSDKdoesnotprovideanycodeforregisteringwithAPNSorforhandlingremotepushnotifications.
DeviceRequirementsThePushSDKrequiresiOS7.0orgreater.ThePushSDKsupportsiOS9.0asofversion1.4.0.
RequiredSetup
GettingStartedInordertoreceivepushmessagesfromthePushServerinyouriOSapplication,youwillneedtofollowthesesteps:
ConfigureiOSPushNotificationsonAppleDeveloper
IfyouarenotfamiliarwiththestepstosetupanapplicationonAppleDeveloperMemberCenterandsetitupforpushnotifications,seetheinstructionsbelow.
YouwillneedtocreateanExplicit App Id with Push Notifications enabled.
NotethatyoucanNOTuseaWildcardAppIDinanapplicationwithpushnotifications.
ConfigureiOSPushNotificationsonthePushDashboard
CreateyourapplicationandplatformsonthePCFMobileServicesPushDashboard.Youwillneedtwoplatforms–onefordevelopmentmodeandone
©CopyrightPivotalSoftwareInc,2013-2018 34of98 1.6
forproduction.EachofthesetwoplatformswillneedtheirownApplePushNotificationService(APNS)SSLcertificates;thedevelopmentplatformneedsasandboxSSLcertificateandtheproductionplatformneedsaproductionSSLcertificate.YouwillneedtoexportbothofthesecertificatesandtheirassociatedprivatesigningkeysasP12 filesusingtheKeychain AccessprogramonourMacOSmachine.Thistaskisbeyondthescopeofthisdocument(seethedocumentationforthePushNotificationServiceDashboard).AftersettingupyourplatformsintheadministrationconsolemakesuretonotethePlatform UUIDandPlatform SecretparametershavebeendefinedunderConfigurationforbothplatforms.Youwillneedthembelow.
YoucanfindstepsonhowtocreateyourapplicationandplatformsonPCFMobileServicesPushDashboardnotes:PushDashboardDocument
LinktotheFramework1. DownloadtheprojectframeworkfromPivotalNetworkandaddittoyourprojectinXcode.Youcandraganddropthe.frameworkfileintoyour
projectintheProjectNavigatorview.MakesuretoenableCopy items if needed.
2. GototheBuildSettingsinXcode.GototheGeneraltab.RemovePCFPush.frameworkfromtheLinked Frameworks And Libraries.AddPCFPush.frameworktothelistofEmbedded Binaries.
3. GotoBuildSettingsinXcode,thennavigatedowntotheLinkingsectionandadd-ObjCtoOther Linker Flags.
NOTE:ifyouaretargetingiOS7.0thenyouwillhavetocompileandlinktheSDKfromsource.iOS7.0doesnotsupportiOS8.0frameworks.
SetupyourPivotal.plistfileCreateaPivotal.plistfileinyourproject’srootdirectory.Thefollowingkeysarerequired:
Key Type Required? Description
pivotal.push.serviceUrl String YES TheURLofthePCFPushNotificationServiceAPIServer.
pivotal.push.platformUuidDevelopment String YES TheplatformUUIDofyourpushdevelopmentplatform.
pivotal.push.platformSecretDevelopment String YES Theplatformsecretofyourpushdevelopmentplatform.
pivotal.push.platformUuidProduction String YES TheplatformUUIDofyourpushproductionplatform.
pivotal.push.platformSecretProduction String YES Theplatformsecretofyourpushproductionplatform.
pivotal.push.sslCertValidationMode String NOCanbesetto default , trustall , pinned ,or callback .MoredetailsbelowintheSSLAuthenticationsection.
pivotal.push.pinnedSslCertificateNames Array NOAlistofSSLcertificatesinthe DER formatstoredintheapplicationbundlethatareusedduringpinnedSSLauthentication.
pivotal.push.areAnalyticsEnabled Boolean NOSetto NO inordertodisablethecollectionofpushanalyticsatruntime.Ifthisparameterisomittedthenanalyticsareassumedtobeenabled.
Noneoftheabovevaluesmaybe nil .Noneoftheabovevaluesmaybeempty.
The pivotal.push.platformUuidDevelopment and pivotal.push.platformSecretDevelopment parametersshouldbethedevelopment platform UUIDandsecretvaluesfromthePushDashboard.ThePushClientSDKusesthisplatformifitdetectsthattheAPNSSandboxenvironmentisbeingusedatruntime.Thesevaluesmaynotbeemptyor nil .
The pivotal.push.platformUuidProduction and pivotal.push.platformSecretProduction parametersshouldbetheproduction platform UUIDandsecretvaluesfromthePushDashboard.NotethatifyouarejusttryingthePushClientSDKoutanddon’thaveanactualproductionenvironmentsetupthenyoucanputdummydatainthesefields.Thesevaluesmaynotbeemptyor nil .
Forinstructionsonconvertingyour PEM certificatefilesto DER ,seetheOpenSSLdocumentation .
Notethatthe pivotal.push.trustAllSslCertificates propertywasremovedinPCFPushClientSDK1.3.3.
RegisterforPushNotificationswithAPNSYouwillneedtoregisteryourappforpushnotificationswithAPNS.Addthefollowingcodetoyour application:didFinishLaunchingWithOptions: methodinyourapplicationdelegate.
©CopyrightPivotalSoftwareInc,2013-2018 35of98 1.6
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{//RegisterforpushnotificationswiththeApplePushNotificationService(APNS).////OniOS8.0+youneedtoprovideyourusernotificationsettingsbycalling//[UIApplication.sharedDelegateregisterUserNotificationSettings:]andthen//[UIApplication.sharedDelegateregisterForRemoteNotifications];////On<iOS8.0youneedtoprovideyourremotenotificationsettingsbycalling//[UIApplication.sharedDelegateregisterForRemoteNotificationTypes:].Thereareno//usernotificationsettingson<iOS8.0.////Ifthislinegivesyouacompilererrorthenyouneedtomakesureyouhaveupdated//yourXcodetoatleastXcode6.0://if([applicationrespondsToSelector:@selector(registerUserNotificationSettings:)]){
//iOS8.0+UIUserNotificationTypenotificationTypes=UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound;//ProvidedifferentnotificationtypesifyouneedthemUIUserNotificationSettings*settings=[UIUserNotificationSettingssettingsForTypes:notificationTypescategories:nil];//Providecustomcategoriesifyouneedthem[applicationregisterUserNotificationSettings:settings];[applicationregisterForRemoteNotifications];
}else{
//<iOS8.0UIRemoteNotificationTypenotificationTypes=UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound;//Providedifferentnotificationtypesifyouneedthem[applicationregisterForRemoteNotificationTypes:notificationTypes];}
returnYES;}
Ifusinggeofencesyouwillalsoneedtorequestauthorizationforlocationserviceshere(i.e.: [self.locationManagerrequestAlwaysAuthorization] ).PleaseseetheGeofencessectionbelow.
Thenotificationtypesfor<iOS8.0aredescribedintheUIApplicationClassReference .
NotethattheOSwilldisplayadialogboxonthescreenatruntimetoconfirmtherequestednotificationtypestotheuserwhentheappattemptstoregisterforpushnotificationsthefirsttime.
RegisterforPushNotificationswithPivotalCFIncludethefollowingheaderinyourapplicationdelegateclass:
#import<PCFPush/PCFPush.h>
Inyourapplicationdelegate’s application:didRegisterforRemoteNotifications: methodputthefollowingcode:
©CopyrightPivotalSoftwareInc,2013-2018 36of98 1.6
//ThismethodiscalledwhenAPNSregistrationsucceeds.-(void)application:(UIApplication*)appdidRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{NSLog(@"APNSregistrationsucceeded!");
//APNSregistrationhassucceededandprovidedtheAPNSdevicetoken.StartregistrationwithPCFPush//NotificationServiceandpassittheAPNSdevicetoken.////Required:Createafileinyourprojectcalled"Pivotal.plist"inordertoprovideparametersforregisteringwith//PCFPushNotificationService////Optional:YoucanprovideacustomuserIDtoassociateyourdevicewithitsuser.////Optional:Youcanalsoprovideasetoftagstosubscribeto.////Optional:Youcanalsoprovideadevicealias.Theuseofthisdevicealiasisapplication-specific.//Werecommendthatyouusetheuser'sdevicenametopopulatethisfield.////Optional:Youcanpassblockstogetcallbacksafterregistrationsucceedsorfails.//[PCFPushregisterForPCFPushNotificationsWithDeviceToken:deviceTokentags:YOUR_TAGSdeviceAlias:YOUR_DEVICE_ALIAScustomUserId:YOUR_CUSTOM_USER_IDareGeofencesEnabled:ARE_GEOFENCES_ENABLEDsuccess:^{NSLog(@"CFregistrationsucceeded!");}failure:^(NSError*error){NSLog(@"CFregistrationfailed:%@",error);}];}
The YOUR_TAGS parameterisaparameterthatprovidesasetofthetagsthatyou’dliketheapplicationtosubscribeto.ThisparametershouldbeanNSSet objectcontainingasetof NSString objects.IfyoupassintagsviathisregistermethodthenyouneedtoprovideALLtagsthattheuserhassubscribedtoeachtimeregistrationiscalled.Tomanageyourtagsyoucanalsocallthe [PCFPushsubscribeToTags:success:failure:] method(describedbelow).
The YOUR_DEVICE_ALIAS parameterisacustomparameterthatyoucanusetoidentifyauser’sdevice(eg:ausermayhavemultipledevices)-thisisforfutureuse.Werecommendthatyouusetheuser’sdevicenametopopulatethisfield(e.g.: UIDevice.currentDevice.name ).
The YOUR_CUSTOM_USER_ID parameterisanothercustomparameterthatyoucanusetoassociatethisdevicewiththeuser.ItispossibletotargetpushnotificationstocustomuserIDs.Ifyoudon’twanttousethecustomuserIDthenyoucansetthisargumentto nil oranemptystring.CustomuserIDsaretreatedascase-sensitive.Formoreinformation,seeRegisteringwithaCustomUserID.
The ARE_GEOFENCES_ENABLED isa BOOL valuethatturnsthegeofencesfeatureonandoff(describedbelow).
Allofthe deviceAlias , tags , success ,and failure parametersareoptionalandmaybesetto nil .
Youcancallthe [PCFPushregisterForPCFPushNotificationsWithDeviceToken:tags:deviceAlias:customUserId:areGeofencesEnabled:success:failure:] methodwheneveryourparameterizationchangesduringruntime(e.g.:whenyouwanttoupdatethedevicealias).Itisnotharmfultocallthismethodseveraltimesduringthelifetimeofaprocess.
RegistrationExamplesExample1:RegisteringforPushNotificationswithnooptions,tags,andwithoutgeofences.
-(void)application:(UIApplication*)appdidRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{[PCFPushregisterForPCFPushNotificationsWithDeviceToken:deviceTokentags:nildeviceAlias:nilcustomUserId:nilareGeofencesEnabled:NOsuccess:^{NSLog(@"CFregistrationsucceeded!");}failure:^(NSError*error){NSLog(@"CFregistrationfailed:%@",error);}];}
Example2:RegisteringforPushNotificationswithacustomeruserIDusingtheuser’saccountname(forexample).
©CopyrightPivotalSoftwareInc,2013-2018 37of98 1.6
-(void)application:(UIApplication*)appdidRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{[PCFPushregisterForPCFPushNotificationsWithDeviceToken:deviceTokentags:nildeviceAlias:nilcustomUserId:@"[email protected]"//User'saccountnameareGeofencesEnabled:NOsuccess:^{NSLog(@"CFregistrationsucceeded!");}failure:^(NSError*error){NSLog(@"CFregistrationfailed:%@",error);}];}
Example3:RemovingtheregistrationforthecustomuserID(whichwillpreventtheuserfrombeingtargetedbytheircustomuserID).
-(void)application:(UIApplication*)appdidRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{[PCFPushregisterForPCFPushNotificationsWithDeviceToken:deviceTokentags:nildeviceAlias:nilcustomUserId:@""//Removetheuser'saccountname.Canuseniloremptystring.areGeofencesEnabled:NOsuccess:^{NSLog(@"CFregistrationsucceeded!");}failure:^(NSError*error){NSLog(@"CFregistrationfailed:%@",error);}];}
Example4:Subscribingtoseveraltopicsonanewsservice.
-(void)application:(UIApplication*)appdidRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{[PCFPushregisterForPCFPushNotificationsWithDeviceToken:deviceTokentags:[NSSetsetWithArray:@[@"breaking_news",@"local_news"]]deviceAlias:nilcustomUserId:nilareGeofencesEnabled:NOsuccess:^{NSLog(@"CFregistrationsucceeded!");}failure:^(NSError*error){NSLog(@"CFregistrationfailed:%@",error);}];}
Example5:Unsubscribingfromthe“breaking_news”tagwhileremainingsubscribedtothe“local_news”tag.
-(void)application:(UIApplication*)appdidRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{[PCFPushregisterForPCFPushNotificationsWithDeviceToken:deviceTokentags:[NSSetsetWithObject:@"local_news"]deviceAlias:nilcustomUserId:nilareGeofencesEnabled:NOsuccess:^{NSLog(@"CFregistrationsucceeded!");}failure:^(NSError*error){NSLog(@"CFregistrationfailed:%@",error);}];}
ReceivingPushNotificationsToreceivepushnotificationsyoucanimplementthefollowingcodeinyourapplicationdelegateclass.
VERY IMPORTANT:Youmustcallthe [PCFPush didReceiveRemoteNotification:completionHandler:] methodinyourapplicationdelegateapplication:didReceiveRemoteNotification:fetchCompletionHandler method,asdemonstratedbelow.
©CopyrightPivotalSoftwareInc,2013-2018 38of98 1.6
//ThismethodiscalledwhenAPNSsendsapushnotificationtotheapplication.-(void)application:(UIApplication*)applicationdidReceiveRemoteNotification:(NSDictionary*)userInfo{[selfhandleRemoteNotification:userInfo];}
//ThismethodiscalledwhenAPNSsendsapushnotificationtotheapplicationwhentheapplicationis//notrunning(e.g.:inthebackground).RequirestheapplicationtohavetheRemoteNotificationBackgroundModeCapability.-(void)application:(UIApplication*)applicationdidReceiveRemoteNotification:(NSDictionary*)userInfofetchCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler{[selfhandleRemoteNotification:userInfo];
//IMPORTANT:InformPCFPushNotificationServicethatthismessagehasbeenreceived.[PCFPushdidReceiveRemoteNotification:userInfocompletionHandler:^(BOOLwasIgnored,UIBackgroundFetchResultfetchResult,NSError*error){
if(completionHandler){completionHandler(fetchResult);}}];}
//Thismethodiscalledwhentheusertouchesoneoftheactionsinanotificationwhentheapplicationis//notrunning(e.g.:inthebackground).iOS8.0+only.-(void)application:(UIApplication*)applicationhandleActionWithIdentifier:(NSString*)identifierforRemoteNotification:(NSDictionary*)userInfocompletionHandler:(void(^)())completionHandler{NSLog(@"Handlingaction%@formessage%@",identifier,userInfo);if(completionHandler){completionHandler();}}
-(void)handleRemoteNotification:(NSDictionary*)userInfo{if(userInfo){NSLog(@"Receivedpushmessage:%@",userInfo);}else{NSLog(@"Receivedpushmessage(nouserInfo).");}}
Ifyoudonotcall [PCFPushdidReceiveRemoteNotification:completionHandler:]
thentheSDKwillnotbeabletofetchgeofenceupdatesnorwillitbeabletocapture
pushanalyticsdata.
OptionalItems
EnableordisablepushanalyticsVersion1.3.3ofthePCFPushClientSDKsupportsthecollectionofsomesimplepushanalyticsdata:
Receivingpushnotifications
Openingpushnotifications
Triggeringgeofences
Analyticsareenabledbydefault.Youcandisableitbysettingthe pivotal.push.areAnalyticsEnabled BOOLEANparameterinyour pivotal.plist fileto NO .Ensurethatyouhaveanup-to-dateversionofthePCFPushAPIserverandthatitisgenerating receiptId dataintheremotenotificationsthatitgenerates.
InorderfortheSDKtocapturepushanalyticsdatayouwillneedtomakesuretocallthe [PCFPushdidReceiveRemoteNotification...] methodinyourapplication:didReceiveRemoteNotification: handler,asdescribedintheReceivingPushNotificationssectionabove.
Ensureyourthattheremote notificationsbackgroundmodehasbeensetforyourprojecttargetconfigurationinordertocaptureanalyticsdatawhenpushnotificationsarereceivedbythedevicewhenyourapplicationisinthebackground.
NOTE:Ifaremotenotificationdoesnothavethe "content-available":1 fieldinitspayloadandiftheuserdoesnottouchthenotificationthentherewillbenoanalyticseventloggedforreceivingthenotificationwhentheapplicationisinthebackground(sinceiOSdoesnotcalltheapplicationfortheremotenotificationsinthebackgroundwithout "content-available":1 ).
©CopyrightPivotalSoftwareInc,2013-2018 39of98 1.6
SubscribingtoTagsThe [PCFPushsubscribeToTags:success:failure:] methodallowsyoutomanageyourtagsafterregistrationhascompleted.Ifyoucallthismethodbeforeregistrationiscompletethenanerrorwilloccur.Thisparametershouldbean NSSet objectcontainingasetof NSString objects.
Ingeneral,anapplicationshouldkeeptrackofallofthetagsitiscurrentlysubscribedto.Wheneveryoucall[PCFPushregisterForPCFPushNotificationsWithDeviceToken:tags:deviceAlias:customUserId:areGeofencesEnabled:success:failure:] or [PCFPushsubscribeToTags:success:failure:] youneedtopassALLofthetagsthattheapplicationiscurrentlysubscribedto.Ifyouwanttoaddnewtagsyoumustprovidethemalongsidethetagsyouarecurrentlysubscribedto.IfyouomitsometagsthentheSDKwillthinkthatyouwanttounsubscribefromthosetags.
UnregisteringfromPivotalCloudFoundryPushNotificationServiceThe [PCFPushunregisterFromPCFPushNotificationsWithSuccess:failure:] methodallowsyoutounregisterfrompushnotificationsfromPCF.AfterunregisteringPCFwillstopsendingthedeviceanynotifications.
ReadingtheDeviceUUIDInordertotargetindividualdevicesforremotenotificationsusingthePCFPushNotificationServiceyouwillneedtotargettheDevice UUIDassignedtoeachdevicebytheservice.YoucanreadtheDeviceUUIDatruntimeanytimeafterasuccessfulregistrationwiththeservicebycallingthe[PCFPushdeviceUuid] method.Thismethodwillreturn nil ifthedeviceisnotcurrentlyregisteredwiththePCFPushNotificationService.
Example:
[PCFPushregisterForPCFPushNotificationsWithDeviceToken:deviceTokentags:nildeviceAlias:UIDevice.currentDevice.namecustomUserId:nilareGeofencesEnabled:YESsuccess:^{PCFPushLog(@"TheDeviceUUIDis\"%@\".",[PCFPushdeviceUuid]);
//Note:addcodetotransmitthedeviceUuidtoyourmiddlewareserver.
}failure:^(NSError*error){PCFPushLog(@"CFregistrationfailed:%@",error);}];
GeofencesGeofencesarenewlysupportedinversion1.3.0ofthePushNotificationService.UsingthisserviceyouwillbeabletoregisterpushnotificationsthatyourappuserswillseewhentheyenterorexitcertaingeographicregionsthatyoudefineonthePushNotificationServiceDashboard.
Inordertosetupyourapptoreceivegeofencenotifications,followthesesteps.
Step1-Setyourbackgroundmodes
Ensureyourlocation updatesandremote notificationsbackgroundmodeshavebeensetforyourprojecttargetcapabilities.Bothofthesemodesarerequiredforyourapplicationtofetchandmonitorgeofenceupdatesfromtheserver.
©CopyrightPivotalSoftwareInc,2013-2018 40of98 1.6
Step2-Setrequireddevicecapabilities
Addlocation-servicesandgpstoyourapplicationInfo.plistfileunder“Requireddevicecapabilities”.
Step3-Setyourlocationusagedescription
IfthisisthefirsttimethatyourappisusinganylocationservicesthenyouwillneedtosetthetextthatisdisplayedoniOS8.0+whentheappfirstrequeststhepermissiontoreadyourcurrentdevicelocation.Youcansetthistextbysettingthe NSLocationAlwaysUsageDescription keyinyourapp’sInfo.plistfile(containedinSupportingFilesfolderbydefault).e.g.:“YourAppNamewouldliketoreadyourcurrentlocationandmonitorgeofences(ifenabled).”
©CopyrightPivotalSoftwareInc,2013-2018 41of98 1.6
Step4-LinktoCoreLocation
EnsurethatyourappislinkedtotheCoreLocationframework.InXcode,gotoyourapptargetsbuildphasesscreenandadd CoreLocation.framework totheLink Binary With Librariesbuildphase.
Step5-Enablegeofences
Inordertoenablegeofencesatruntimeyouwillneedtopass YES tothe areGeofencesEnabled argumentwhenyoucallthe[PCFPushregisterForPCFPushNotificationsWithDeviceToken... methodinyourapplicationdelegate.Ifthisparameterissetto NO thennogeofencesfeatureswillbeavailableatruntime.Anygeofencesthatmayhavebeenmonitoredbeforewillbeclearedandwillnolongerbemonitored.
Step6-Authorizelocationservices
IfusinggeofencesoniOS8.0+devicesyouwillneedtoaddthemethodcalltorequestpermissionfromtheusertoreadthecurrentdevicelocation.Agoodplaceforthatisinyourapplicationdelegate application:didFinishLaunchingWithOptions method.Thiscallwillshowanalertdialogboxtotheuserthatshows
©CopyrightPivotalSoftwareInc,2013-2018 42of98 1.6
the NSLocationAlwaysUsageDescription textinyourPLISTfile.
-(BOOL)application:(UIApplication*)applicationdidFinishLaunchingWithOptions:(NSDictionary*)launchOptions{//RegisterforpushnotificationswiththeApplePushNotificationService(APNS).////OniOS8.0+youneedtoprovideyourusernotificationsettingsbycalling//[UIApplication.sharedDelegateregisterUserNotificationSettings:]andthen//[UIApplication.sharedDelegateregisterForRemoteNotifications];////On<iOS8.0youneedtoprovideyourremotenotificationsettingsbycalling//[UIApplication.sharedDelegateregisterForRemoteNotificationTypes:].Thereareno//usernotificationsettingson<iOS8.0.////Ifthislinegivesyouacompilererrorthenyouneedtomakesureyouhaveupdated//yourXcodetoatleastXcode6.0://if([applicationrespondsToSelector:@selector(registerUserNotificationSettings:)]){
//iOS8.0+UIUserNotificationTypenotificationTypes=UIUserNotificationTypeAlert|UIUserNotificationTypeBadge|UIUserNotificationTypeSound;UIUserNotificationSettings*settings=[UIUserNotificationSettingssettingsForTypes:notificationTypescategories:nil];[applicationregisterUserNotificationSettings:settings];[applicationregisterForRemoteNotifications];
//NOTE:addthisblocktoenablelocationservicesforgeofencesif([applicationrespondsToSelector:@selector(registerUserNotificationSettings:)]){self.locationManager=[[CLLocationManageralloc]init];[self.locationManagerrequestAlwaysAuthorization];//iOS8.0+only}
}else{
//<iOS8.0UIRemoteNotificationTypenotificationTypes=UIRemoteNotificationTypeAlert|UIRemoteNotificationTypeBadge|UIRemoteNotificationTypeSound;[applicationregisterForRemoteNotificationTypes:notificationTypes];}
returnYES;}
Step7-Addpropertytoapplicationdelegate
Requiredonlyifyouareusinggeofences:addapropertytoyourapplicationdelegateclass(AppDelegate.h)asfollows:
@property(strong,nonatomic)CLLocationManager*locationManager;
Youwillalsoneedtoincludethefollowingheadertothesamefile:
#import<CoreLocation/CoreLocation.h>
Step8-ReceivingLocalNotifications
Ifyoufollowtheabovestepsthenyourapplicationwillbeabletoshowgeofenceswhentheyaretriggered.Geofencesaredeliveredaslocalnotificationstoyourapp.Similartoremotenotifications,localnotificationswillbeautomaticallydisplayedwhenyourapplicationisinthebackgroundbutyouwillneedtoaddyourowncodeinordertodisplaythemwhenyourappisintheforeground.
Ifyouneedtoknowifthegeofencewastriggeredviaan‘enter’or'exit’conditionthenlookatthepivotal.push.geofence_trigger_condition keyintheuserInfodictionaryprovidedwiththelocationnotification.YoucanalsousethisuserInfofieldtodistinguishgeofencelocalnotificationsfromotherkindsoflocalnotifications.
Asanexample,ifyouwanttoprintalogmessagewhenalocalnotificationisreceived:
-(void)application:(UIApplication*)applicationdidReceiveLocalNotification:(UILocalNotification*)notification{NSLog(@"Received%@localnotification'%@'",notification.userInfo[@"pivotal.push.geofence_trigger_condition"],notification.alertBody);}
©CopyrightPivotalSoftwareInc,2013-2018 43of98 1.6
Step9-ReceiveGeofenceStatusUpdates
ThePCFPushNotificationServiceserverwillpushupdatedgeofencestouserdevicesviapushnotifications.Youdon’tneedtodoanymoreworktoprocesstheseupdatesormonitorthesegeofences.Youcanreadthegeofencestatusobjecttofindoutifanyproblemsoccurduringthesebackgroundupdates.Theseerrorscanbereporteddirectlytoyourapplicationifyouaddanobservertothe PCF_PUSH_GEOFENCE_STATUS_UPDATE_NOTIFICATIONnotificationin NSNotificationCenter .
Example:
Youcansubscribetothegeofenceupdatenotificationwiththefollowingcodeinyourprogram.Youcouldputitinyouroneofyourviewcontrollersoryourapplicationdelegate,asyouseefit.
[[NSNotificationCenterdefaultCenter]addObserver:selfselector:@selector(geofenceStatusChanged:)name:PCF_PUSH_GEOFENCE_STATUS_UPDATE_NOTIFICATIONobject:nil];
Theabovemethodcallwillcausethe geofenceStatusChanged methodtobecalled.Youwillneedtodefinethismethodyourselfinthesameclass(orinwhateverobjectinstanceyoupassedto NSNotificationCenter above:
-(void)geofenceStatusChanged:(NSNotification*)notification{PCFPushGeofenceStatus*status=[PCFPushgeofenceStatus];NSLog(@"%@",status);}
SSLAuthenticationTheproperty pivotal.push.sslCertValidationMode allowstheapplicationtoacceptthefollowingsupportedSSLAuthenticationmodes:
1. default:WhentheserviceURLisnotHTTPSorwhenusingaservertrustedcertificatethismodeshouldbeset.
2. trustall:WhenusingadevelopmentenvironmentthereistheabilitytotrustallcertificateswhileusingaHTTPSserviceURL.Thismodereplacesthepreviousproperty(priortov1.3.3) pivotal.push.trustAllSslCertificates .
3. pinned:Toensurenomaninthemiddleattacksthismodeshouldbeset.TheservercertificatewillbeverifiedwiththelocalcopyofthecertificatereferredtoasCertificatePinningauthentication.Whenthismodeissetthelocalcopyofthecertificate(s)shouldbeprovidedwiththepivotal.push.pinnedSslCertificateNames arrayproperty.AllcertificatesprovidedwillbestoredintheassetsfolderoftheapplicationinaDERformat.
4. callback:WhenacustomSSLauthenticationschemaisrequiredthismodecanbesetwherebythespecificauthenticationlogicwouldbeaddedinsidetheapplicationasacallbacktotheSDK.Thecallbackmustbeablockthatreceivesthearguments (NSURLConnection*,NSURLAuthenticationChallenge*) andwillbecalledwhenattemptingtomakeanHTTPSnetworkrequest.
Inorderforthismethodtotakeeffectyouwillneedtocallitboth [PCFPushregisterForPCFPushNotificationsWithDeviceToken:...] andalso [PCFPushdidReceiveRemoteNotification:...]
.
example:
©CopyrightPivotalSoftwareInc,2013-2018 44of98 1.6
@implementationAppDelegate
...
-(PCFPushAuthenticationCallback)getAuthenticationCallback{return^(NSURLConnection*connection,NSURLAuthenticationChallenge*challenge){//HandletheSSLchallengehere!};}
-(void)application:(UIApplication*)appdidRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken{[PCFPushsetAuthenticationCallback:[selfgetAuthenticationCallback]];...[PCFPushregisterForPCFPushNotificationsWithDeviceToken:deviceToken...];}
-(void)application:(UIApplication*)appdidReceiveRemoteNotification:(NSDictionary*)userInfofetchCompletionHandler:(void(^)(UIBackgroundFetchResult))completionHandler{[PCFPushsetAuthenticationCallback:[selfgetAuthenticationCallback]];...[PCFPushdidReceiveRemoteNotification:userInfocompletionHandler:...];}
...
@end
PleaseseeApple’sdocumentationfortheNSURLConnectionDelegateconnection:willSendRequestForAuthenticationChallenge methodformoreinformationonhowtohandlethecallback.
SettingcustomHTTPrequestheadersInordertoinjectcustomheadersintoanyHTTPrequestsmadebythePushSDKyoushouldcallthe [PCFPushsetRequestHeaders:] methodwithadictionaryoftherequiredHTTPheadervalues.Allvaluesshouldbepairsof(NSString,NSString)values.Notethatyoucannotprovideany'Authorization’or'Content-Type’headersviathismethod;theywillbeignoredbythePushSDK.
Inorderforthismethodtotakeeffectyouwillneedtocallit registerForPCFPushNotificationsWithDeviceToken .
example:
[PCFPushsetRequestHeaders:@{@"Cookie:"@"MY_SESSION_COOKIE",@"My-Special-Custom-Header":@"My-Special-Custom-Value"}];...[PCFPushregisterForPCFPushNotificationsWithDeviceToken:@"My-Device-Token"......];
Appendix
iOS9.0+Notes-AppTransportSecurityAppleintroducedAppTransportSecurity(ATS) iniOS9.0.ATSwill,bydefaultblockallHTTPconnections.IfyouwanttouseHTTPiniOS9.0appsthenyouwillhavetosetupanATSexceptioninyour Info.plist fileandenable NSExceptionAllowsInsecureHTTPLoads foryourdesiredsubdomain.AppledoesnotrecommendHTTPandrecommendsusingATSassoonaspossible.
IfyouareusingHTTPSandneedtouseanyofthe“trustall”,“pinned”,or“callback”sslCertValidationModesthenyouwillalsoneedtoenableNSExceptionAllowsInsecureHTTPLoads foryourdesiredsubdomain.EnablinginsureHTTPloadswillallowthecustomSSLvalidationinthePCFPushSDK.
Exampleinfo.plist:
©CopyrightPivotalSoftwareInc,2013-2018 45of98 1.6
<key>NSAppTransportSecurity</key><dict><key>NSExceptionDomains</key><dict><key>yourserver.com</key><dict><!--Includetoallowsubdomains--><key>NSIncludesSubdomains</key><true/><!--IncludetoallowHTTPrequestandcustomSSLvalidation--><key>NSExceptionAllowsInsecureHTTPLoads</key><true/></dict></dict></dict>
SettingupyourapponAppleDeveloperMemberCenterIfyouarenotfamiliarwithhowtocreateanapplicationontheAppleDeveloperMemberCenter,followthestepsbelow.Thisinformationissubjecttochangeandyoumayfindmoreup-to-dateinformationatAppDistributionGuide .
GeneratinganAppID1. LogintoyourAppleDeveloperAccount.
2. Clickthe Certificates,Identifiers&Profiles linkontherightsideofthepage.
3. Onthe iOSApps sectionontheleftsideofthepageclickthe Identifiers link.
4. Youshouldnowbeonthe iOSAppIDs page.Clickthe + buttononthetoprighttocreateyourAppID.
5. Fillinyour AppIDDescription and BundleID under AppIDSuffix → ExplicitAppID .This BundleID isthesame BundleIdentifier thatwasgeneratedwhenyoucreateyourapplicationinXcode.
6. Scrolldowntothe AppServices Sectionandunder EnableServices check PushNotifications .Once PushNotifications areenabledclickthe Continue
button.
7. Lookoverthesettingsonthenextpageandclick Submit whenyou’veverifiedyoursettings.
8. Youshouldnowseeyour AppID inthelistonthe iOSAppIDs page.
PushSandboxSSLCertificate1. Clickonyournewlycreated AppID andclickthe Edit button.
2. Scrolldowntothe PushNotifications section.Wewillnowgeneratea DevelopmentSSLCertificate .Navigatetothe DevelopmentSSLCertificate sectionandthenclickonthe CreateCertificate button.
3. Followtheinstructionsonthe AboutCreatingaCertificateSigningRequest(CSR) page:Open Keychain Access .
©CopyrightPivotalSoftwareInc,2013-2018 46of98 1.6
Withinthe Keychain Access drop down menu select Certificate Assistant →Request a Certificate from a Certificate Authority .Typeinyouremailaddress.Ensure Saved to disk ischecked.Clickthe Continue button.SavethecertificatetodiskandRevealinFinder.
4. Gobacktoyourwebbrowsertothe AboutCreatingaCertificateSigningRequest(CSR) pageandclick Continue .Choosethecertificatesigningrequestthatyoujustsavedtodiskandclick Generate .Youwillneedtodownloadthisfileandopenit. KeychainAccess shouldopenthisfile.Ifprompted,addittothe login keychain.Youshouldbeabletoseethiscertificateifyounavigatetothe MyCertificates sectionin KeychainAccess .
5. Exportyourcertificateasa p12 filewithapassword.Navigatetoyour My Certificates sectionin Keychain AccessExpandyourcertificateandselectbothitems.
Rightclickonthecertificateandselect Export 2 items...Namethiscertificatewithyour Bundle ID andappend Sandbox totheend,andensurethattheFileFormatisPersonal Information Exchange (.p12)
Selectapasswordtoprotectthiscertificatewith,youwillneedthispasswordwhenyousetupthePCFPushserverthoughthePCFPushDashboard.Savethis .p12 fileinalocationyouwillremember.
Generateyourprovisioningprofile1. Gotothe ProvisioningProfiles ontheleftandclickthe Development link.
2. Clickthe + atthetoprightofthepageby iOSProvisioningProfiles
3. Gotothe Development sectionandselect iOSAppDevelopment .Clickthe Continue buttontoproceed.
4. Selectthe AppID thatyoucreatedabove.Clickthe Continue buttontoproceed.
5. Selectyoursigningcertificate.Clickthe Continue buttontoproceed.
6. Selectyourdesiredtestdevices.
7. Clickthe Generate buttontogenerateyourprovisioningprofile.
8. Clickthe Download buttontodownloadyourprovisioningprofile.OpenthisfileandgobacktoXcode.
9. InXcode,makesureyouareonthe BuildSettings tabandnavigatedownto ProvisioningProfile .Selecttheprovisioningprofilethatyoujustcreated.Thisprofilewillonlyshowupifyouopenedthefilefromthepreviousstep.
TroubleshootingPleaseseeourtroubleshootingguide
©CopyrightPivotalSoftwareInc,2013-2018 47of98 1.6
Android Push Client SDK
SampleAppYoucanfindtheAndroidSampleApponGithub .
VersionThisdocumentcoverstheAndroidPushClientSDKv1.6.0.
Olddocumentation:
v1.4.0
v1.3.3
v1.3.2
v1.3.1
v1.3.0
v1.0.4
TherewasnoreleaseofthePushAndroidSDKforv1.5.0.
FeaturesTheAndroidPushClientSDKisalight-weightlibrarythathelpsyourapp:
1. RegisterforpushnotificationswithGoogleCloudMessaging(GCM)andaninstanceofthePCFPushNotificationService .
2. Receivepushmessagessentviathesameframeworks.
3. Monitorgeofencesthathavebeenconfiguredfromacentralserver.
DeviceRequirementsThePushSDKrequiresAndroid API level 16orgreater.SupportforAndroid14and15wasdroppedasofPushSDKv1.4.0.
TheGoogle Play Servicesappmustbeinstalledonthedevicebeforeyoucanregisteryourdeviceorreceivepushmessages.Typically,theuserneedstobeloggedintoaGoogleaccountaswell.Mostdevicesalreadyhavethisappinstalled,butsomeoddonesmaynot.YoushouldbeabletoreceivepushnotificationsonaAndroidemulateddeviceifithastheGoogle APIsinstalled.
RequiredSetup
GettingStartedToreceivepushmessagesfromthePCFPushNotificationServiceinyourAndroidapp,youneedtocreateaprojectwithintheGoogleDevelopersConsole.SeeGoogleDevelopersConsolebelow.
SetupyourappandanAndroid PlatformonthePCFPushNotificationServiceDashboard.Thistaskisbeyondthescopeofthisdocument,butnotethatyouneedtheAPI KeyparameterfromGoogleCloudConsoleabove.AftersettingupyourAndroidplatforminPCFMobileServices,notedownthePlatform UUIDandPlatform Secretparameters.Youneedthembelow.Atthistime,theAndroidPushsoftwaremakesnodistinctionbetweendeveloperandproductionmodes.
Forinformationonhowtocreateyourappandplatforms,seeUsingtheDashboard.
©CopyrightPivotalSoftwareInc,2013-2018 48of98 1.6
LinktoPCFPushSDKDownloadthePCFPushClientSDKforAndroidfromPivotalNetwork .TheClientSDKisdeliveredasanAndroidLibrary(i.e.:an“AAR”file).CopytheAARfileintothe libs directoryofyourprojectandensurethatthefollowinglinelineisinthe dependencies sectionofyourmodule-level build.gradle file:
repositories{mavenCentral()flatDir{dirs'libs'}}
Additionally,addthefollowingdependencytothe dependencies sectionofyourmodule-level build.gradle file:
dependencies{compile(name:'PCFPush-1.6.0',ext:'aar')compile'com.google.code.gson:gson:2.4'compile'com.google.android.gms:play-services-location:8.4.0'compile'com.google.android.gms:play-services-gcm:8.4.0'compile'com.android.support:support-annotations:23.3.0'compile'com.android.support:appcompat-v7:23.3.0'}
Youneedtodefineandusethefollowing permission elementinthe manifest elementofyourapp’s AndroidManifest.xml file.Ensurethatthebaseofthepermission nameisyourapp’spackage name:
<permissionandroid:name="[YOUR.PACKAGE.NAME].permission.C2D_MESSAGE"android:protectionLevel="signature"/>
<uses-permissionandroid:name="[YOUR.PACKAGE.NAME].permission.C2D_MESSAGE"/>
Youneedtoaddthefollowing receiver tothe application elementofyourapp’s AndroidManifest.xml file.Ensurethatyousetthecategory nametoyourapp’spackage name:
<receiverandroid:name="io.pivotal.android.push.receiver.GcmBroadcastReceiver"android:permission="com.google.android.c2dm.permission.SEND"><intent-filter><actionandroid:name="com.google.android.c2dm.intent.RECEIVE"/><categoryandroid:name="[YOUR.PACKAGE.NAME]"/></intent-filter></receiver>
Configuration:SetUpYourpivotal.propertiesFileCreateapivotal.propertiesfileinyourproject’s src/main/assets or src/main/res/raw directory.Thefollowingpropertiesarerequired:
Property Required Description
pivotal.push.serviceUrl Yes TheURLofthePCFPushServer.
pivotal.push.platformUuid Yes TheplatformUUIDofyourpushplatformonthePCFPushserver.
pivotal.push.platformSecret Yes TheplatformsecretofyourpushplatformonthePCFPushserver.
pivotal.push.gcmSenderId Yes TheprojectnumberassignedbyGoogleCloudConsole.
pivotal.push.sslCertValidationMode No Canbesetto default , trustall , pinned ,or callback .MoredetailsbelowintheSSLAuthenticationsection.
pivotal.push.pinnedSslCertificateNames NoIfusing pinned SSLvalidationmodethenthispropertyshouldbealistofSSLcertificatesinthe DER formatstoredintheassetsdirectory.Thelistisspaceseparated.
pivotal.push.areAnalyticsEnabled No Setto false todisablethecaptureofpushanalyticsdata.Defaultsto true .
Noneoftheabovevaluesmaybe null .Noneoftheabovevaluesmaybeempty.
The pivotal.push.platformUuid and pivotal.push.platformSecret parametersaretheplatform UUIDandsecretvaluesfromthePushDashboard.IfyouusetheSDKv1.6,thenuseUUIDandsecretofplatformtype Android .
Forinstructionsonhowtoconvertyour PEM certificatefilesto DER ,seetheOpenSSLdocumentation .
Notethatthe pivotal.push.trustAllSslCertificates propertywasremovedinPCFPushClientSDKv1.3.3.
©CopyrightPivotalSoftwareInc,2013-2018 49of98 1.6
RegistrationItisrecommendedthatyouinitializethePushClientSDKinyourapp’sprimary Activity subclass’ onCreate method.
Addthefollowinglinesofcodetotheinitializationsectionofyourapp.YouneedaContext objecttopasstothe getInstance method,soyoushouldtrytoaddthiscodetoyour Activity class.Intheexamplebelowthe Context isthe this objectpassedtothe getInstance method(assumingthatwe’reinanActivity):
try{//RegistrationListenerisoptionalandmaybe`null`.Push.getInstance(this).startRegistration(DEVICE_ALIAS,CUSTOM_USER_ID,TAGS,ARE_GEOFENCES_ENABLED,newRegistrationListener(){
@OverridepublicvoidonRegistrationComplete(){Log.i("MyLogTag","RegistrationwithPCFPushsuccessful.");}
@OverridepublicvoidonRegistrationFailed(Stringreason){Log.e("MyLogTag","RegistrationwithPCFPushfailed:"+reason);}});}catch(Exceptione){Log.e("MyLogTag","RegistrationwithPCFPushfailed:"+e);}
TheDEVICE_ALIASisacustomfieldthatyoucanusetodifferentiatethisdevicefromothersandisintendedforfutureuse.Ifyoudon’twanttousethedevicealiasthenyoucansetthisargumentto null oranemptystring.Atthistimeyoucannotusethedevicealiasfortargetingpushnotifications.Werecommendthatyouusetheuser’sdevicenametopopulatethisfield.
TheCUSTOM_USER_IDisanothercustomfieldthatyoucanusetoassociatethisdevicewiththeuser.ItispossibletotargetpushnotificationstocustomuserIDs.Ifyoudon’twanttousethecustomuserIDthenyoucansetthisargumentto null oranemptystring.CustomuserIDsaretreatedascase-sensitive.
TheTAGSparameterisa Set<String> oftagsthatyourappwouldliketosubscribeto.Therearemanypossibleusesoftagsbuttheyaredependentonyourparticularusecases.Alwaysensurethatyouprovideallofthetagsthatyou’dliketobesubscribedto;ifyouomittagsinfuturecallstotheregistermethodthentheSDKthinksthatyouaretryingtounsubscribefromthosetags.Iftherearenotagsthatyouwanttoregistertothenyoucansetthisargumentto null .Tagsaretreatedascase-insensitive.
TheARE_GEOFENCES_ENABLEDisa boolean valuethatturnsthegeofencesfeatureonandoff(describedbelow).Ifyouwanttousegeofencesinyourapp,thenrequestpermissiontoreadthedevicelocation.IfyouwanttosupportAndroidMarshmallow,youmustwriteextracodetorequestthedevicelocation.Thisextracodeisdescribedinthegeofencessectionbelow.
Youshouldonlyhavetocall startRegistration onceinthelifetimeofyourprocess–butcallingitmoretimesisnotharmful.The startRegistration methodisasynchronousandwillreturnbeforeregistrationiscomplete.Ifyouneedtoknowwhenregistrationiscomplete(orifitfails),thenprovideaRegistrationListener asthesecondargument.
RegistrationExamplesExample1:RegisteringforPushNotificationswithnooptions,tags,withoutgeofencesandwithnocallback.
Push.getInstance(this).startRegistration(null,null,null,false,null);
Example2:RegisteringforPushNotificationswithacustomeruserIDusingtheuser’saccountname(forexample).
finalStringcustomUserId="[email protected]";//Youruser'saccountnamePush.getInstance(this).startRegistration(null,customUserId,null,false,null);
Example3:RemovingtheregistrationforthecustomuserID(whichpreventstheuserfrombeingtargetedbytheircustomuserID).
finalStringcustomUserId="";//CanusenulloremptystringtoremovethecustomuserIDPush.getInstance(this).startRegistration(null,customUserId,null,false,null);
Example4:Subscribingtoseveraltopicsonanewsservice.
©CopyrightPivotalSoftwareInc,2013-2018 50of98 1.6
finalSet<String>tags=newHashSet<>();tags.add("breaking_news");tags.add("local_news");Push.getInstance(this).startRegistration(null,null,tags,false,null);
Example5:Unsubscribingfromthe“breaking_news”tagwhileremainingsubscribedtothe“local_news”tag.
finalSet<String>tags=newHashSet<>();tags.add("local_news");Push.getInstance(this).startRegistration(null,null,tags,false,null);
ReceivingPushNotificationsToreceivepushnotificationsinyourapp,youneedtoaddacustom Service toyourappthatextendsthe GcmService providedintheSDK.TheintentthatGCMsendsispassedtoyourservice’s onReceiveMessage method.Hereisasimpleexample:
publicclassMyPushServiceextendsGcmService{
@OverridepublicvoidonReceiveMessage(Bundlepayload){if(payload.containsKey("message")){finalStringmessage=payload.getString("message");handleMessage(message);}}
privatevoidhandleMessage(Stringmsg){//Yourcodehere.Displaythemessage//onthedevice'sbarasanotification.}}
Finally,youneedtodeclareyourserviceinyourAndroidManifest.xmlfile.
<serviceandroid:name=".MyPushService"android:exported="false"/>
OptionalItems
PushAnalyticsVersion1.3.3ofthePCFPushClientSDKsupportsthecollectionofsomesimplepushanalyticsdata:
Receivingpushnotifications
Openingpushnotifications
Triggeringgeofences
Analyticsareenabledbydefault.Youcandisableitbysettingthe pivotal.push.areAnalyticsEnabled parameterinyour pivotal.properties fileto false .Ensurethatyouhaveanup-to-dateversionofthePCFPushAPIserverandthatitisgenerating receiptId dataintheremotenotificationsthatitgenerates(whichisactivatedbydefault).
SincethenotificationcapabilitiesonAndroidareverydiversetheSDKdoesn’tdoanyworktohelpappsdisplaythem.Itreliesonyourapptodecidehowtodisplayandhandleallpushnotifications.Assuch,thereisnowayfortheSDKtoknowwhentheusertouchesanotificationandopensyourapp.IfyouwanttocollectmetricsabouthowmanyusersareopeningthenotificationsinyourappthentheSDKreliesonyourapptoinformit.YouneedtocallthelogOpenedNotification methodinthe Push classwiththesame Bundle thatwasdeliveredinthepushnotification.
Thecapturingpushanalyticsdatarequiresv1.3.2ofthePushAPIserver.TheSDKcheckstheserverversionbeforecapturinganyanalyticsdata.Iftheserverversionistooold,thennoanalyticsdataisrecorded.TheSDKcheckstheserverversiononceevery24hoursinreleasebuildsandevery5minutesindebugbuilds.
e.g.:
©CopyrightPivotalSoftwareInc,2013-2018 51of98 1.6
Let’ssaythatyouusethiscodetodisplayapushnotificationinyoursubclassof GcmService :
@OverridepublicvoidonReceiveMessage(Bundlepayload){finalStringmessage=payload.getString("message");
finalNotificationManagernotificationManager=(NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
finalIntentintent=newIntent(this,MyAppsMainActivity.class);intent.setAction("YOUR_CUSTOM_NOTIFICATION_ACTION_NAME");intent.putExtras(payload);finalPendingIntentcontentIntent=PendingIntent.getActivity(this,0,intent,0);
finalNotificationCompat.Builderbuilder=newNotificationCompat.Builder(this).setSmallIcon(R.drawable.ic_your_app_logo).setContentTitle(getString(R.string.app_name)).setContentIntent(contentIntent).setContentText(msg);
notificationManager.notify(NOTIFICATION_ID,builder.build());}
Thenyoucanusethefollowingcodeintheopenedactivitytoreportthatthenotificationhasbeenopened:
publicclassMyAppsMainActivityextendsActivity{...
@OverrideprotectedvoidonResume(){super.onResume();
finalIntenti=getIntent();if(i.getAction().equals("YOUR_CUSTOM_NOTIFICATION_ACTION_NAME")){Push.getInstance(this).logOpenedNotification(i.getExtras());}}
Notethatitisimportanttopasstheentireremotenotificationpayload Bundle intothe logOpenedNotification method.Thisexampleaccomplishesthisrequirementbysavingthepayload Bundle inthe Intent Extras inthe PendingIntent passedtothenotification.
TagsIfanyofyourtagschangeduringthelifetimeofyourprocess(e.g.:yourappwantstochangethelistoftagsthatithassubscribedto)thencallsubscribeToTags withyournewsetofparameters.Example:
//TheSubscribeToTagsListenerisoptionalandmaybe`null`.Push.getInstance(this).subscribeToTags(TAGS,newSubscribeToTagsListener(){@OverridepublicvoidonSubscribeToTagsComplete(){Log.i("MyLogTag","SuccessfullysubscribedtotagswithPCFPush.");}
@OverridepublicvoidonSubscribeToTagsFailed(Stringreason){Log.e("MyLogTag","FailedtosubscribetotagswithPCFPush:"+reason);}});
UnregistrationIfyouwanttounregisterfrompushnotificationsthenyoucancallthe startUnregistration method:
©CopyrightPivotalSoftwareInc,2013-2018 52of98 1.6
//TheUnregistrationListenerisoptionalandmaybe`null`.Push.getInstance(this).startUnregistration(newUnregistrationListener(){@OverridepublicvoidonUnregistrationComplete(){Log.i("MyLogTag","SuccessfullyunregisteredfromPCFPush.");}
@OverridepublicvoidonUnregistrationFailed(Stringreason){Log.e("MyLogTag","FailedtounregisterfromPCFPush:"+reason);}});
ReadingtheDeviceUUIDInordertotargetindividualdevicesforremotenotificationsusingthePCFPushNotificationService,youneedtotargettheDeviceUUIDassignedtoeachdevicebytheservice.YoucanreadtheDeviceUUIDatruntimeanytimeafterasuccessfulregistrationwiththeservicebycallingthe getDeviceUuidmethod.Thismethodreturns null ifthedeviceisnotcurrentlyregisteredwiththePCFPushNotificationService.
Example:
Push.getInstance(this).startRegistration(deviceAlias,subscribedTags,areGeofencesEnabled,newRegistrationListener(){
@OverridepublicvoidonRegistrationComplete(){Log.i("MyLogTag","DeviceUuid:"+Push.getInstance(this).getDeviceUuid());}
@OverridepublicvoidonRegistrationFailed(Stringreason){Log.e("MyLogTag","FailedtounregisterfromPCFPush:"+reason);}});
SSLAuthenticationTheproperty pivotal.push.sslCertValidationMode allowstheapptoacceptthefollowingsupportedSSLAuthenticationmodes:
1. default:WhentheserviceURLisnotHTTPSorwhenusingaservertrustedcertificatethismodeshouldbeset.
2. trustall:WhenusingadevelopmentenvironmentthereistheabilitytotrustallcertificateswhileusingaHTTPSserviceURL.Thismodereplacesthepreviousproperty(priortov1.3.3) pivotal.push.trustAllSslCertificates .
3. pinned:Toensurenomaninthemiddleattacksthismodeshouldbeset.TheservercertificateisverifiedwiththelocalcopyofthecertificatereferredtoasCertificatePinningauthentication.Whenthismodeissetthelocalcopyofthecertificate(s)shouldbeprovidedwithaspace-separatedlistinthe pivotal.push.pinnedSslCertificateNames property.AllcertificatesprovidedarestoredintheassetsfolderoftheappinaDERformat.
4. callback:WhenacustomSSLauthenticationschemaisrequiredthismodecanbesetwherebythespecificauthenticationlogicwouldbeaddedinsidetheappasacallbacktotheSDK.Youneedtocreateyourownimplementationofaclassextendingthe CustomSslProvider interfaceanddeclareitinyourmanifestfileina <meta-data> elementinyour <application> element.Thenameofthemeta-datais“io.pivotal.android.push.CustomSslProvider”andthevalueofthemeta-datashouldbethenameofyourcustomSSLproviderclass(withitsfullpackagename).Thisclassmusthaveadefault(empty)constructorandisinstantiatedatruntimewhennetworkrequestsaremadetoHTTPSserviceendpoints.
exampleCustomSslProviderimplementation:
©CopyrightPivotalSoftwareInc,2013-2018 53of98 1.6
publicclassMyCustomSslProviderimplementsCustomSslProvider{
publicMyCustomSslProvider(){/*defaultconstructorisrequired*/}
@OverridepublicSSLSocketFactorygetSSLSocketFactory()throwsNoSuchAlgorithmException,KeyManagementException{
TrustManager[]trustAllCerts=newTrustManager[]{FILLMEIN};
SSLContextcontext=SSLContext.getInstance("TLS");//or"SSL"-pleaselookattheJavadocumentationcontext.init(null,trustAllCerts,null);
returncontext.getSocketFactory();}
@OverridepublicHostnameVerifiergetHostnameVerifier(){returnnewHostnameVerifier(){publicbooleanverify(Stringhostname,SSLSessionsession){FILLMEIN}};}}
exampleAndroidManifest.xml:
<application>
...
<meta-dataandroid:name="io.pivotal.android.push.CustomSslProvider"android:value="YOURPACKAGENAME.MyCustomSslProvider"/>
...
</application>
SettingCustomHTTPRequestHeadersInordertoinjectcustomheadersintoanyHTTPrequestsmadebythePushSDKyoushouldcallthe setRequestHeaders methodinthe Push classwithaMap<String,String> oftherequiredHTTPheadervalues.Notethatyoucannotprovideany‘Authorization’or'Content-Type’headersviathismethod;theyareignoredbythePushSDK.
Inorderforthismethodtotakeeffectyouneedtocallit startRegistration , subscribeToTags ,oranyothermethodsthatmakenetworkrequests.
GeofencesGeofencesarenewlysupportedinv1.3.0ofthePushNotificationService.Usingthisservice,youcanregisterpushnotificationsthatyourappusersseewhentheyenterorexitcertaingeographicregionsthatyoudefineonthePushNotificationServiceDashboard.
Tosetupyourapptoreceivegeofencenotifications,performthefollowingsteps.
Step1:SetUpYourAndroidManifest.xmlFile
Addthesetwopermissionstothe application elementofyourAndroidManifest.xmlfile.
<uses-permissionandroid:name="android.permission.ACCESS_FINE_LOCATION"/><uses-permissionandroid:name="android.permission.RECEIVE_BOOT_COMPLETED"/>
Step2:SetUpYourPushService
Youneedtooverridethefollowingtwomethodsinyourappcustom Service (seeStep7above).
©CopyrightPivotalSoftwareInc,2013-2018 54of98 1.6
@OverridepublicvoidonGeofenceEnter(Bundlepayload){Log.i("MyLogTag","Enteredgeofence"+payload.getString("message"));//Processgeofenceenterevent}
@OverridepublicvoidonGeofenceExit(Bundlepayload){Log.i("MyLogTag","Exitedgeofence"+payload.getString("message"));//Processgeofenceexitevent}
Step3:(Optional)ReceiveGeofenceStatusUpdates
ThePCFPushNotificationServiceserverpushesupdatedgeofencestouserdevicesviapushnotifications.Youdon’tneedtodoanymoreworktoprocesstheseupdatesormonitorthesegeofences.Youcanreadthegeofencestatusobjecttofindoutifanyproblemsoccurduringthesebackgroundupdates.Theseerrorscanbereporteddirectlytoyourappifyoucreatea BroadcastReceiver thatlistensto io.pivotal.android.push.geofence.UPDATE intents.
Example:
Createaclasscalled MyGeofenceUpdateBroadcastReceiver :
publicclassMyGeofenceUpdateBroadcastReceiverextendsBroadcastReceiver{
@OverridepublicvoidonReceive(Contextcontext,Intentintent){finalGeofenceStatusstatus=Push.getInstance(context).getGeofenceStatus();//Readgeofencestatusif(status!=null){if(status.isError()){Toast.makeText(context,status.getErrorReason(),Toast.LENGTH_LONG).show();}Toast.makeText(context,"Numberofcurrentlymonitoringgeofences:"+status.getNumberCurrentlyMonitoringGeofences(),Toast.LENGTH_LONG).show();}}}
Youcanconfigureyour BroadcastReceiver classtolistentogeofenceupdatesbyaddingthefollowingelementinyour AndroidManifest.xml :
<receiverandroid:name=".MyGeofenceUpdateBroadcastReceiver"android:exported="false"><intent-filter><actionandroid:name="io.pivotal.android.push.geofence.UPDATE"/></intent-filter></receiver>
Step4:Requestdevicelocationpermission(Androidv6.0Marshmallowandup)
Androidv6.0Marshmallowintroducedanewsystemforobtaininguserpermissionfor“dangerous”operations.Ifyouwanttousegeofencesinyourappthenyouneedtorequestthepermissiontoreadthedevicelocationatruntime.BeforeAndroidv6.0Marshmallowitwassufficienttosimplyaddauses-permission elementtoyour AndroidManifest.xml fileinordertorequestpermissionasdescribedinStep1above.InAndroidv6.0Marshmallowyoumuststilladdthe uses-permission elementtoyour AndroidManifest.xml filebutyoumustalsorequestpermissionfromtheuserdirectlyatruntime.We’veaddedahelpermethodtothePushSDKtohelpyouwiththistaskbutyoustillneedtodosomeoftheworkyourselfinyourapp.
Inoneofyourapp’sprimary Activity classes,youneedtoaddthefollowingcodetoyour onCreate methodBEFOREyouinitializethePushSDK.Thedialogboxmustcontainamessagethatexplainstoyouruserwhyyourappneedstoreadthedevicelocation.Youmaystyleorthemethisdialogboxanywaythatyouwouldliketo.Youonlyneedtogivethedialogboxonebutton:“OK”.
©CopyrightPivotalSoftwareInc,2013-2018 55of98 1.6
if(ARE_GEOFENCES_ENABLED){
//IfyouwanttousegeofencesandaretargettingAndroidMarshmalloworgreater,thenyoumustspecifically//asktheuserforpermissiontoreadthedevicelocation.ThefollowingDialogclassisusedtoexplain//totheuserwhyyourappisrequestingpermissiontoreadthedevicelocation.
finalDialogdialog=newAlertDialog.Builder(this).setMessage("Thisapplicationneedspermissiontoreadthedevicelocationinordertosendyounotificationswhenyouentercertainlocations.").setPositiveButton("OK",null).create();
finalbooleanwerePermissionsAlreadyGranted=Push.getInstance(this).requestPermissions(this,REQUEST_PERMISSION_FOR_GEOFENCES_RESPONSE_CODE,dialog);
if(werePermissionsAlreadyGranted){
//IfPush.requestPermissionsreturnstruethenACCESS_FINE_LOCATIONpermissionhasalreadybeengranted//andwecanimmediatelybeginpushregistration.
startPushRegistrationWithGeofencesEnabled(true);}
}else{startPushRegistrationWithGeofencesEnabled(false);}
Ifthepermissiontoreadthedevicelocationhasnotyetbeengranted,thenGoogleshowsasystemdialogboxtorequestpermission.Itmayalsoshowyouruser-defineddialogbox.Aftertheuserpresses“Allow”or“Deny”thenGooglecallsthe onRequestPermissionsResult callbackinthesameactivity:
@OverridepublicvoidonRequestPermissionsResult(intrequestCode,@NonNullString[]permissions,@NonNullint[]grantResults){
//ThiscallbackisinvokedbyAndroidaftertheuserdecidestoallowordenypermissionforACCESS_FINE_LOCATION.//IfPush.requestPermissionsreturnsfalsethenyouneedtowaitforthiscallbackbeforeattempting//toregisterforpushes.
if(requestCode==REQUEST_PERMISSION_FOR_GEOFENCES_RESPONSE_CODE&&permissions[0].equals(android.Manifest.permission.ACCESS_FINE_LOCATION)){if(grantResults[0]==PackageManager.PERMISSION_GRANTED){startPushRegistrationWithGeofencesEnabled(true);}else{startPushRegistrationWithGeofencesEnabled(false);}}}
The REQUEST_PERMISSION_FOR_GEOFENCES_RESPONSE_CODE valueisauniqueintegerthatisechoedbacktothe onRequestPermissionsResult methodaftertheuserallowsordeniesthepermission.Youcanselectanyintegerthatyouwouldlike.
//Requestcodewhenrequestingpermissiontousegeofences.privatestaticfinalintREQUEST_PERMISSION_FOR_GEOFENCES_RESPONSE_CODE=27;//Yourfavouriteinteger
Step5:Enablegeofences
Inordertoenablegeofencesatruntimeyouneedtopass true tothe areGeofencesEnabled argumentwhenyoucallthe startRegistration methodinyourappmainactivity.Ifthisparameterissetto false thennogeofencesfeaturesareavailableatruntime.Anygeofencesthatmayhavebeenmonitoredbeforeareclearedandarenolongermonitored.
The startPushRegistrationWithGeofencesEnabled methodintheaboveexamplewillfinallyinitializethePushSDK.Ifthedevicelocationpermissionwasnotgrantedthenyoushoulddisablegeofences.Notethattheuserisabletoalloworrevokethispermissionatanyothertimeinthefuture.ItisimportanttorequestthispermissionEVERYTIMEyouinitializeyourPushSDK:
©CopyrightPivotalSoftwareInc,2013-2018 56of98 1.6
privatevoidstartPushRegistrationWithGeofencesEnabled(booleanareGeofencesEnabled){
Push.getInstance(this).startRegistration(DEVICE_ALIAS,TAGS,areGeofencesEnabled,newRegistrationListener(){
@OverridepublicvoidonRegistrationComplete(){printMessage("Registrationsuccessful.");}
@OverridepublicvoidonRegistrationFailed(Stringreason){printMessage("Registrationfailed.Reason:"+reason);}});}
Appendix
GoogleDevelopersConsole1. LogintoGoogleDevelopersConsole .YouneedaGoogleaccount.
2. ClickCreate Project.
3. EnteraProject Nameandleavetheauto-generatedProject IDfielduntouched.ClickCreate.
4. Waituntiltheprojectiscompleted,thismighttakeacoupleofminutes.Afterthis,youareontheprojectpage.
5. NoteatthetopyourProject Number.Thisvalueshouldbeinlightgraytext.Makenoteofthisvaluebecauseyouneeditlater.Makesureyouusethenumericprojectnumber.DonotusetheprojectIDwiththewords.
6. Ontheleft,intheAPIs & Authsection,clickAPIs.
7. IntheBrowse APIsfield,enterGoogle Cloud MessagingandensurethatGoogle Cloud Messaging for AndroidisenabledbyclickingEnable API.
8. OntheleftclicktheCredentialslinkwhichisdirectlybelowtheAPIslink.
9. FindPublic API AccessonthepageandclicktheCreate new Keybuttonbelow.ClickServer keywhenthedialogpopsup.
10. Inthetextfieldinsidethedialogboxenter 0.0.0.0/0 andclicktheCreatebutton.
11. MakenoteoftheAPI KEYvaluebecauseyouneeditlater.
TroubleshootingSeeTroubleshooting.
©CopyrightPivotalSoftwareInc,2013-2018 57of98 1.6
Windows Phone 8.1 Push Client SDK
SampleAppYoucanfindtheWindowsPhoneSampleAppongithub
FeaturesThePivotalCloudFoundryMobileServices PushClientSDKisalight-weightlibrarythatwillhelpyourapplicationregisterwithWindowsNotificationService(WNS)andaninstanceofthePCFMobileServicesPushNotificationserver.
TheSDKdoesnotprovideanycodeforhandlingremotepushnotification.
DeviceRequirementsThePushSDKrequiresWP8.1.
GettingStartedInordertoreceivepushmessagesfromthePushServerinyourWP8.1application,youwillneedtofollowthesesteps:
1. YoumusthaveaWindowsStoreaccount,andyourappmustberegisteredwiththewindowsstore,andmustyouhaveacertificateforreceivingpushes.Followtheinstructionshere:
http://msdn.microsoft.com/en-us/library/windows/apps/hh465407.aspx
Finally,youneedtoassociateyourappwiththewindowsstore.RightclickonyourprojectinVisualStudio.SelectStore.Select‘AssociateAppwiththeStore…’FollowMicrosoft’son-screeninstructionstocompleteapp-to-storeassociation.
1. Setupyourapplication,environment,andavariantonthePCFMobileServicesadministrationconsole.Thistaskisbeyondthescopeofthisdocument,butpleasenoteyouwillneedtheTLScertificateabove.AftersettingupyourvariantinPCFMobileServices,makesuretonotetheVariantUUIDandVariantSecretparameters.Youwillneedthembelow.
2. AddareferencetotheSDKNuGetpackagetoyourproject.Ifyoudon’thaveaccesstotheNuGet,youcouldsimplyobtainthecompiledDLLfiles.PleasecontactthePCFMobileServicesteamforhelp.
3. Addthefollowinglinesofcodetotheinitializationsectionofyourapplication.
MSSParametersparameters=newMSSParameters(variant_uuid,variant_secret,base_server_url,server_name,device_alias,tags);awaitMSSPush.SharedInstance.RegisterForPushAsync(parameters);
The variant_uuid , variant_secret ,and server_name aredescribedabove.The base_server_url parameteristhebaseurlofyourpushserver.The device_aliasparameterisacustomfieldthatyoucanusetodifferentiatethisdevicefromothersinyourownpushmessagingcampaigns;canbenull.The tagsparameterisacustomfieldthatyoucanusetodifferentiateregistrationsinyourownpushmessagingcampaigns;canbenull.
Youshouldonlyhavetocall RegisterForPushAsync onceinthelifetimeofyourprocess-butcallingitmoretimesisnotharmful.The RegisterForPushAsyncmethodisasynchronousandwillreturnbeforeregistrationiscomplete.Toknowwhenregistrationiscomplete(orifitfails)andobtainthePushNotificationChannel ,providean Action<PushNotificationChannel> asthesecondargument.
ThePCFMobileServicesPushSDKtakescareofthefollowingtasksforyou:
RegisteringwithWNS.
SendingyourpushnotificationchannelURItotheback-end(i.e.:thePCFMobileServices).
Re-registeringafterthepushnotificationchannelURIoranyotherregistrationparametersareupdated.
©CopyrightPivotalSoftwareInc,2013-2018 58of98 1.6
APIsYoucanusethefollowingAPIsforthePushNotificationService:
PushAPI
RegistrationAPI
RegistrationsAPI
TopicsAPI
CustomUserIDsAPI
SchedulesAPI
GeofencesAPI
©CopyrightPivotalSoftwareInc,2013-2018 59of98 1.6
Push
Pushamessage
POST/v1/pushPushamessageouttoalistofdevicesordevicestargetedbyplatform.
Authentication: HTTP Basic application_uuid:api_key
Query Parameters: None
RequestBody:Therearemanypossibleoptionsfortherequestbody.AlloftheoptionsarelistedintheJSONtextexamplebelow.NotethatmostoftheindividualJSONfieldsareoptional.Theoptionsyouneedtousearedescribedbelow.Severalexamplesareillustratedbelow.
Themessage→bodyfieldintheJSONrequestbodyisthe messagethatissuppliedinnotificationstoremotedevices.Itwillbeoverriddenbyanyplatform-specificcustommessagebodydata.
Inparticular,iOSdeviceswillreceivethemessage→bodyfieldastheiralertmessageunlessthecustom→ios→alert→bodyfieldispopulated.Androiddeviceswillreceivethemessage→bodyfieldintheirpayloadmessagefieldunlessthecustom→android→messagefieldispopulated.
ResponseData,status:200(OK)Thefieldsreturnedbythe/v1/pushPOSTAPIdependonthetypeofpushnotificationthatwasrequested: or .
IfthepushisgivenscheduleAtorscheduleInfieldsthenthepushis tobedeliveredinthefuture.Thesepusheswillreturnaschedule_idfieldintheresponsedata.Theseschedule_idvaluescanbeusedinthe/v1/scheduleAPIstoupdateorcancelthescheduledpushbeforeitisdelivered.
Otherwisethepushwillbequeuedtobesent .Inthiscase,theresponsewillalsocontainareceipt_idfieldthatcanbeusedtofollowthepushnotificationdeliverystatusintheauditlogs.
ResponseData
{"schedule_id":"",#onlyreturnedifthepushnotificationisascheduledpush"receipt_id":""#onlyreturnedifthepushisbeingdeliveredimmediately.}
pushesaredescribedfurtherbelow.
Targeting/AudienceSelectionYoucantargetyourpushnotificationsinmanyways:
Byplatform(s).e.g.:“ios”,“android”.
BydeviceUUID(s):
DevicesUUIDsaredeterminedby:
thedeviceregistrationprocessinthePCFPushClientSDKs.SeethedocumentationfortheiOSorAndroidSDKs.orbythe/v1/registrationPOST/PUTAPIsifyouareregisteringyourdeviceswithoutusingtheClientSDKs.
Bytopic(s):
©CopyrightPivotalSoftwareInc,2013-2018 60of98 1.6
Topicsarecreated:
implicitlywhendevicessubscribedtothem.Seethe/v1/registrationPOST/PUTAPIs.orwhenthe/v1/topicsPOSTAPIisused.
ByCustomUserID:
CustomUserIDsarecreatedviatheRegisteradeviceAPI/v1/registrationPOSTAPIs.SendingapushtoaCustomUserID:
thepushwillbesentsimultaneouslytoalldevicesregisteredwiththisCustomUserID.
ByCustomUserIDandTopic(s):
SendingapushtoaCustomUserIDandTopic(s):
thepushwillbesentsimultaneouslytoalldevicesregisteredwiththisCustomUserIDandalldevicesregisteredwithanyoftheprovidedTopic(s).
Key Description
devicesAlistofupto4096deviceUUIDstotarget.ThesedeviceUUIDsarethesameonesthatarereturnedbythePCFPushClientSDKsafterregistrationorbythe/v1/registrationHTTPPOSTcallifyouareregisteringyourdeviceswithoutusingtheClientSDKs.
topicsAlistofup1024topics(formerlytags)towhichdevicesmaybesubscribed.Onlydevicessubscribedtooneofmoreofthelistedtopicswillbetargeted.DevicesselectwhichtopicstosubscribetobycallingtheappropriatesubscribeToTopicsmethodsintheclientSDKsorbycallingthe/v1/registrationHTTPPOSTorPUT.
platforms Alistofplatformstobetargeted.Availableplatformsare‘ios’,'android’,'windows8’,'windowsPhone’,'bb10’(ifenabled).
platformDEPRECATED.Possiblevaluesare'all’,'ios’,'android’,'windows8’,'windowsPhone’,'bb10’(ifenabled).If'platforms’isalsopopulatedtheplatform(s)selectedherewillbeaddedtolistofplatforms.
interactive-onlyIfsettotruethenonlythosedevicesthatcanacceptinteractivepushesaretargetted.AtthistimeonlyiOS8+orAndroid4.1+devicesareconsideredtosupportinteractivepushes.
custom_user_idsAlistofIDsfordevicesthatismeaningfultoyoursystem,suchastheirlogin.ThesameCustomUserIDcanbeusedtorefertomultipledevices.
LIMITSPushingtomultipletargetsisboundedbythefollowinglimitsperrequest:
Devices:4096
CustomUserIds:4096
Topics:1024
NOTESAtleastoneofdevices,topics,platforms,orplatformisrequired.
deviceswilloverrideanyothertargetingtype.Anytopics,platforms,orplatformtargettingkeywillbeignoredifthereisadeviceskey.
topicsandplatformscanbeusedinacomplementarywaytopushamessagetojustasubsetofusers(Seeexamplebelow).
Devicesonlyneedtobesubscribedtoatleastoneofthetopicsinthetargettingdatainordertoreceivethemessage(Seeexamplebelow).ThereisnowayusingthePushAPItosendamessagetoadevicethatissubscribedto ofthetopicsinalist.
TargetExamplesSendingpushmessagestothreespecificdevices(specifiedbytheirdeviceUUIDs):
{..."target":{"devices":["device_uuid1","device_uuid2","device_uuid3"]}...}
©CopyrightPivotalSoftwareInc,2013-2018 61of98 1.6
Sendingpushestoalldevices(regardlessofplatform)subscribedtooneoftwospecifictopics(adeviceonlyneedstobesubscribedtooneofthetopicsinthelistoftopicsinordertoreceivethemessage).
{..."target":{"topics":["exciting_topic","pedantic_topic"]}...}
SendingpushestoalliOSdevices:
{..."target":{"platforms":["ios"]}...}
Sendingpushestoall“Android”devicessubscribedtoonespecifictopic:
{..."target":{"platforms":["android"],"topics":["best_topic_ever"]}...}
Sendingpushestointeractiveonlydevices:
{..."target":{"platforms":["android","ios"],"interactive-only":true}...}
SendingpushestodevicesregisteredwithaCustomUserID:
{..."target":{"custom_user_ids":["some_customer_user_id","some_other_custom_user_id"]}...}
SendingpushestodevicesregisteredwithaCustomUserIDanddevicesregisteredwithTopic(s):
{..."target":{"custom_user_ids":["some_customer_user_id"],"topics":["exciting_topic","pedantic_topic"]}...}
SendingpushestodevicesregisteredwithCustomUserIDsanddevicesregisteredwithTopic(s):
{..."target":{"custom_user_ids":["some_customer_user_id1","some_customer_user_id2"],"topics":["exciting_topic","pedantic_topic"]}...}
©CopyrightPivotalSoftwareInc,2013-2018 62of98 1.6
SettingExpirationTimeonPushesThe“expiryTime”fieldcanbeusedtospecifyatimeafterwhichapushshouldnotbedisplayed.ItshouldbeanEpochtimestampintegerinmilliseconds(i.e.:thenumberofmillisecondssincemidnightJanuary1,1970).IfexpiryTimeisnotsetthebehaviorwillbetheplatformdefault.ForiOS,AndroidandBB10pusheswillbequeuedfordeliveryifthetargetdeviceisunreachableatthetimeofthepushanddeliveredassoonasitisreachable.IfexpiryTimeissetandthethedevicebecomesreachableAFTERtheexpirytime,thepushwillnotbedelivered.
Windows8behaviorissimilarfortileandbadgenotificationsbutonlyonetileandonebadgenotificationwillbequeued.SeethePushnotificationservicerequestandresponseheaders documentationformoreinformation.
IMPORTANT NOTE:
Ifomitted,thedefaultexpirytimeusedforAppledevicesis Integer.MAX_VALUE seconds(i.e.:sometimeintheyear2038).
Ifomitted,thedefaultexpirytimeusedonGCMis4weeks(2,419,200seconds).Themaximumtime-to-liveformessagesdeliveredonGCMisalso4weeks.
Windows8toastnotificationsarenotqueuedandcannothaveanexpirytime.Theywillonlybedeliveredatthetimethepushissentifthetargetdeviceisconnected.
WindowsPhone7hasnoexpiryoption.Insteadpushesfallintooneofthreecategories:immediate,upto450seconds,orupto900seconds.Dependingonthetimesetinthe“expiryTime”field,apushtoWindowsPhone7willbeslottedintooneofthosecategories.SeetheSendingpushnotificationsforWindowsPhone documentation.
ScheduledPushesPushescanbescheduledtobesentatalatertime.UsethescheduleAtfieldtospecifythetimewhenthepushshouldbesent.AswithexpiryTimethisshouldbeanEpochtimestampintegerinmilliseconds.AlternativelyyoucanusethescheduleInfieldtospecifythescheduledtimeasthenumberofsecondsfromthetimetheserverreceivesthepushrequest.NOTE:YoucannotsetboththescheduleAtandscheduleInfieldsatthesametimeasdoingthiswouldresultinanerrormessagefromtheserver.
Ifthescheduledtimeislessthanapreconfiguredtimeinthefuture,thepushwillnotbescheduledandwillbesentimmediately.Bydefaultthisamountis60seconds.
ScheduledPushesExamplesSchedulingapushmessagetobedeliveredforFebruary2,2016at8AM(UTC):
{..."scheduleAt":1454313600000...}
Schedulingapushmessagetobedeliveredtwohoursfromnow:
{..."scheduleIn":7200000...}
CustomFieldsforPlatformspecificPushes
CustomFieldsforiOSPushesThefieldsavailableinthecustomblockforiOSaredescribedhere:
©CopyrightPivotalSoftwareInc,2013-2018 63of98 1.6
{"ios":{"alert":{"body":"iOSonlymessagebody","action-loc-key":"actionKey","loc-key":"localizedStringKey","loc-args":[""],"title":"Title","title-loc-key":"titleKey","title-loc-args":["arg1","arg2"],"launch-image":"Default.png"},"category":"SAMPLE_CATEGORY","badge":1,"sound":"default","content-available":true,#Note-thePushAPIexpectsthisfieldtobeaboolean.(seebelow)"extra":{"freeformcustomdata":"freeformcustomdata",...}}}
extratype:dictionaryornullThispropertycanbeusedtopassfree-formarbitrarypayloaddatatothereceivingiOSdevice.Thisdatawillbepassedinthe userInfo dictionaryintheapplication:didReceiveRemoteNotification callbackintheapplication’sappdelegateclass.Itisuptotheapplicationtousethisdataasitneeds.
alerttype:stringordictionaryIfthispropertyisincluded,thesystemdisplaysastandardalert.Youmayspecifyastringasthevalueofalertoradictionaryasitsvalue.Ifyouspecifyastring,itbecomesthemessagetextofanalertwithtwobuttons:CloseandView.IftheusertapsView,theappislaunched.Alternatively,youcanspecifyadictionaryasthevalueofalert.SeeTable3-2attheAppleDocumentation fordescriptionsofthekeysofthisdictionary.
badgetype:numberThenumbertodisplayasthebadgeoftheappicon.Ifthispropertyisabsentthebadgeisnotchanged.Toremovethebadge,setthevalueofthispropertyto0.
soundtype:stringThenameofasoundfileintheappbundle.Thesoundinthisfileisplayedasanalert.Ifthesoundfiledoesn’texistordefaultisspecifiedasthevalue,thedefaultalertsoundisplayed.Theaudiomustbeinoneoftheaudiodataformatsthatarecompatiblewithsystemsounds;seePreparingCustomAlertSounds fordetails.
content-availabletype:booleanProvidethiskeywithavalueof true toindicatethatnewcontentisavailable.Includingthiskeyandvaluemeansthatwhenyourappislaunchedinthebackgroundorresumed, application:didReceiveRemoteNotification:fetchCompletionHandler: iscalled.(Newsstandappsareguaranteedtobeabletoreceiveatleastonepushwiththiskeyper24-hourwindow).ThePushAPIwilltranslatethevalueofthisfieldto 1 or 0 beforesendingittoAPNS.
titletype:stringAshortstringdescribingthepurposeofthenotification.ThisfieldwasintroducedonAppleWatchbutisalsodisplayedoniOSdevicesasofiOSversion10.0.ThiskeywasaddediniOS8.2.
bodytype:stringThetextofthealertmessage.
title-loc-keytype:stringornullThekeytoatitlestringinthe“Localizable.strings”fileforthecurrentlocalization.Thekeystringcanbeformattedwith %@ and %n$@ specifierstotakethevariablesspecifiedinthetitle-loc-argsarray.SeeLocalizedFormattedStrings formoreinformation.ThiskeywasaddediniOS8.2.
title-loc-argstype:arrayofstringsornullVariablestringvaluestoappearinplaceoftheformatspecifiersintitle-loc-key.SeeLocalizedFormattedStrings formoreinformation.ThiskeywasaddediniOS8.2.
action-loc-keytype:stringornullIfastringisspecified,thesystemdisplaysanalertthatincludestheCloseandViewbuttons.Thestringisusedasakeytogetalocalizedstringinthecurrentlocalizationtousefortherightbutton’stitleinsteadof“View”.SeeLocalizedFormattedStrings formoreinformation.
©CopyrightPivotalSoftwareInc,2013-2018 64of98 1.6
loc-keytype:stringAkeytoanalert-messagestringina“Localizable.strings”fileforthecurrentlocalization(whichissetbytheuser’slanguagepreference).Thekeystringcanbeformattedwith %@ and %n$@ specifierstotakethevariablesspecifiedintheloc-argsarray.SeeLocalizedFormattedStrings formoreinformation.
loc-argstype:arrayofstringsVariablestringvaluestoappearinplaceoftheformatspecifiersinloc-key.SeeLocalizedFormattedStrings formoreinformation.
launch-imagetype:stringThefilenameofanimagefileintheappbundle;itmayincludetheextensionoromitit.Theimageisusedasthelaunchimagewhenuserstaptheactionbuttonormovetheactionslider.IfthispropertyisnotspecifiedthenthesystemeitherusestheprevioussnapshotorusestheimageidentifiedbytheUILaunchImageFilekeyintheapp’s“Info.plist”file,orfallsbackto“Default.png”.ThispropertywasaddediniOS4.0.
PleasechecktheAppledocumentation formoredetailedinformation.
CustomFieldsforAndroidPushesThecustomfieldsforandroidareadictionarythatcancontainanyfieldsrequiredbyyourapplication.Youcanalsospecifyacollapse_keyinthecustomfieldsforAndroid.Amessagewithacollapse_keythathasnotyetbeendeliveredmaybereplacedbyanewermessagewiththesamecollapsekey.PleaseseetheGoogledocumentationoncollapsablemessages .
Otherwise,youcanspecifyanyarbitraryfreeformpayloaddatatodelivertothereceivingAndroiddevice.AllofthefieldsinthisintheandroidelementinthepushrequestwillbesuppliedtothereceivingAndroiddeviceinthe Bundle providedto onReceiveMessage methodintheAndroidapplication’ssubclassof GcmService .Ingeneralthepushmessagedatawouldbeprovidedina message JSONfieldbutitisuptoyourapplicationtousethemessagepayloadasitneeds.
Notethatthe“message”→“body”fieldinthePushrequestbody,ifpresent,willbedeliveredinthe“message”fieldoftheGCMpushnotificationpayload.
CustomFieldsforOtherPlatforms
BB10
Thebb10customfieldconsistsofastringwhichwilloverridethemessagebodyonBlackBerry10.NotethatPCFPushNotificationServicesupportforWindows8isbasic.Pivotaldoesnotprovideanyup-to-dateclientSDKsforBlackBerry10atthistime.
NOTE:ThePCFPushNotificationServicedoesnotshipwithBB10supportenabledduetorestrictionsonredistributionofBlackBerry’spushlibraries.IfyouneedtoenableBB10pushespleasecontactPivotalSupport .
Windows8(WNS)
SeethisreferenceforadescriptionofWindows8pushoptions.NotethatPCFPushNotificationServicesupportforWindows8isbasic.Pivotaldoesnotprovideanyup-to-dateclientSDKsforWindows8atthistime.
WindowsPhone(MPNS)
SeethisreferenceforadescriptionofWindowsPhonepushoptions.NotethatPCFPushNotificationServicesupportforWindows8isbasic.Pivotaldoesnotprovideanyup-to-dateclientSDKsforWindowsPhoneatthistime.
CompleteExamplesUnliketheaboveexamples,theseexampleswillshowthecompletePushrequestbody.
Sendamessagetoalluserssubscribedtothe“local_seminars”topicstoalertthemtoanimportantcommunitymeeting.ThismessageexpiresonthemorningofFridayApril1,2016.
©CopyrightPivotalSoftwareInc,2013-2018 65of98 1.6
{"message":{"body":"TownHallThisThursday:Forging,Cheese,AndYou"},"target":{"topics":["local_seminars"]},"expiryTime":1459468800000}
SendapushtoalliOSandAndroiddevicesthataresubscribedtoone(ormore)ofthe“breaking_news”,“local”,or“dairy”topics.Providesomecustomfieldsthatappscanusetodeeplinktoarticledata.Thismessageisscheduledtobedeliveredintwohours.
{"message":{"custom":{"ios":{"alert":{"body":"BreakingNews:World'sBiggestCheeseForgedAtLocalBakery"},"content-available":true,"extra":{"story_url":"https://my_server/article/123456789"}},"android":{"message":"BreakingNews:World'sBiggestCheeseForgedAtLocalBakery","story_url":"https://my_server/article/123456789"}}},"target":{"topics":["breaking_news","local","dairy"],"platforms":["ios","android"]},"scheduleIn":7200}
Sendapushtooneparticulardeviceinformatingtheuserthattheyhaveonenewemailnotification.Thebadgeontheappiconwillbesetto“1”andasoundwillbeplayed.Someoftheemailmetadataisprovidedinthemessageextrassothattheapplicationcanshowapreviewofthemessage.Themessageisgiventhe“new_email”categorysothatiOS8.0+devicescanprovideappropriateactionbuttonsfortheuser.
{"message":{"custom":{"ios":{"alert":{"body":"You'vegotmail!"},"category":"new_email","badge":1,"sound":"new_email","content-available":true,"extra":{"from":"YourLocalBakery","to":"You","subject":"SpecialDealonCheese","message_body":"PleasecometoyourlocalbakerybeforeFridaytosampleapieceoftheworld'sbiggestcheese."}}}},"target":{"devices":["111-222-333444"]}}
Alloptionsinrequestbodyforpushingamessageouttoalistofdevicesordevicestargetedbyplatform.
©CopyrightPivotalSoftwareInc,2013-2018 66of98 1.6
{"message":{"body":"Messagebody",#Thetextofthepushmessage"custom":{"ios":{"alert":{"body":"iOSonlymessagebody",#Thebodyofthepushmessage"action-loc-key":"actionKey",#(overridesbodydefinedabove)"loc-key":"localizedStringKey","loc-args":["arg1","arg2",...],"title":"Title","title-loc-key":"titleKey","title-loc-args":["arg1","arg2",...],"launch-image":"Default.png"},"category":"SAMPLE_CATEGORY","badge":1,"sound":"default","content-available":true,#Note-thePushAPIexpectsthisfieldtobeaboolean.(seebelow)"extra":{}},"android":{"collapse_key":"collapseKey"},"windows8":{"template_name":"TileSquareBlock","template_fields":{"textField1":"text1","textField2":"text2"},"options":{},"type":"tile"},"windowsPhone":{"template_fields":{"subtitle":"text","parameter":"text"},"template":"toast"},"bb10":"BB10onlymessagebody"}},"target":{"topics":["topic1","topic2",...],"platforms":["platform1","platform2",...],"devices":["device_uuid1","device_uuid2",...],"interactive-only":false,#Eithertrueorfalse"platform":"all"#Oneofthefollowingoptions},#(ios,android,windows8,windowsPhone,bb10)
"scheduleAt":1345852800000,#Epochtimestampinmilliseconds."scheduleIn":0,#Integer(timedeltainseconds)"expiryTime":null#Epochtimestampinmilliseconds.}
©CopyrightPivotalSoftwareInc,2013-2018 67of98 1.6
Registration
GET/v1/registration/:deviceUuidRetrievesadevice’sregistrationforaspecificplatform.
Authentication: HTTP Basic platform_uuid:platform_secret
Query Parameters: None
ResponseData,status:200(OK)
{"os":"",#oneof[ios|android|windowsPhone|windows8]"device_model":"",#devicemodelidentifier"device_manufacturer":"",#devicemanufactureridentifier"device_alias":"",#applicationspecificdevice/useridentifier"device_uuid":"",#uniquedeviceidentifier"registration_token":"",#tokenprovidedbyAPNS(ios),GCM(android),MPNS(windowsPhone),orWNS(windows8)"tags":[#tagsthedevice/userissubscribedto,thiswilloverwriteanyexistingtagsthedevice/userwaspreviouslysubscribedto{"text":""}],"active":"",#canthedevicebetargetedforpushes"os_version":""#deviceversionstring}
GET/v1/registration/count/Returnsthetotalnumberofdeviceregistrationsthathavebeenstoredforoneplatform.
Authentication: HTTP Basic platform_uuid:platform_secret
Query Parameters: None
ResponseData,status:200(OK)Returnsaninteger.
POST/v1/registration/Registeradevicetoanapprelease.Theresponsewillinclude device_uuid .Youshouldsavethisidentifier,asotherregistrationendpointswillrequireit(ex. DELETE ).
Whentheenvironmentvariable push_security_verifyCustomUserId issettotrue(whichisdefault),creatingaregistrationwithacustom_user_id,itisrequiredthatthecustom_user_idisencryptedwithauniqueHMACusingthedevicesharedsecretasthecryptigraphickey.
FormoreinformationseeRegisteringwithaCustomUserID.
Authentication: HTTP Basic platform_uuid:platform_secret
Query Parameters: None
RequestBody:
©CopyrightPivotalSoftwareInc,2013-2018 68of98 1.6
{"device_alias":"string",#applicationspecificdevice/useridentifier.Werecommendthatyouusetheuser'sdevicenameasdevicealias"device_model":"string",#devicemodelidentifier"device_manufacturer":"string",#devicemanufactureridentifier"os":"string",#deviceos,oneof[ios|android|windowsPhone|windows8]"os_version":"string",#deviceversionstring"registration_token":"string",#tokenprovidedbyAPNS(ios),GCM(android),MPNS(windowsPhone),orWNS(windows8)"tags":["tag1","tag2"],#tagsthedevice/userissubscribedto,thiswilloverwriteanyexistingtagsthedevice/userwaspreviouslysubscribedto"custom_user_id":"string"#allowsyoutoregisteradeviceunderanIDthatismeaningfultoyoursystemsuchastheirlogin}
ResponseData,status:200(OK)
{"os_version":"",#osversionstring"tags":[#tagsthatthedevicehassubscribedto{"text":"tag1"},{"text":"tag2"}],"os":"",#oneof[ios|android|windowsPhone|windows8]"device_model":"",#devicemodelidentifier"device_manufacturer":"",#devicemanufactureridentifier"device_alias":"",#applicationspecificdevice/useridentifier"device_uuid":"",#theuniqueidentifierassignedtothedevicebyPushNotifications"registration_token":"",#tokenprovidedbyAPNS(ios),GCM(android),MPNS(windowsPhone),orWPN(windows8)"active":"",#canthedevicebetargetedforpushes"custom_user_id":""#deviceregisteredwithcustomuserid}
LIMITSRegisteringadeviceisboundedbythefollowinglimitsperrequest:
Devices:Auto-Generated
CustomUserIds:1
Tags:1024
Examples:Registeradevice:
{"device_alias":"John'siPhone","device_model":"iPhone6","device_manufacturer":"Apple","os":"ios","os_version":"9.0","registration_token":"b50edac575bfba07dd019b28b2af7189a3ddda17c806ef14a9abbfd00533f67e","tags":["beta","gamma","alpha"],"custom_user_id":"jsmith"}
PUT/v1/registration/:device_uuidUpdatearegistration.Requiresthatthedevice_uuidreturnedwhenyouregisteredissentasaurlparameter.
Whentheenvironmentvariable push_security_verifyCustomUserId issettotrue(whichisdefault),updatingaregistrationwithacustom_user_id,itisrequiredthatthecustom_user_idisencryptedwithauniqueHMACusingthedevicesharedsecretasthecryptigraphickey.
Authentication: HTTP Basic platform_uuid:platform_secret
©CopyrightPivotalSoftwareInc,2013-2018 69of98 1.6
Query Parameters: None
RequestBody:
{"device_alias":"string",#applicationspecificdevice/useridentifier.Werecommendthatyouusetheuser'sdevicenameasdevicealias."device_manufacturer":"string",#devicemanufactureridentifier"device_model":"string",#devicemodelidentifier"os_version":"string",#osversionstring"registration_token":"string",#tokenprovidedbyAPNS(ios),GCM(android),MPNS(windowsPhone),orWPN(windows8)"tags":{"subscribe":["tag1","tag2"],#addnewtagssubscriptionstothedevice/user"unsubscribe":["tag3","tag4"]#removetagsthatthedevice/userissubscribedto},"custom_user_id":"string"#allowsyoutoregisteradeviceunderanIDthatismeaningfultoyoursystemsuchastheirlogin}
Examples:Updatedeviceregistration:
{"device_alias":"JohnSmith'siPhone","device_model":"iPhone6","device_manufacturer":"Apple","os":"ios","os_version":"9.0","registration_token":"b50edac575bfba07dd019b28b2af7189a3ddda17c806ef14a9abbfd00533f67e","tags":["beta","gamma","alpha","delta"],"custom_user_id":"john.smith"}
DELETE/v1/registration/:device_uuidDeletearegistration.Requiresthatthedevice_uuidreturnedwhenyouregisteredissentasaurlparameter
Authentication: HTTP Basic platform_uuid:platform_secret
Query Parameters: None
RequestBody:None.
ResponseData,status:204(NOCONTENT)
©CopyrightPivotalSoftwareInc,2013-2018 70of98 1.6
RegistrationsAPIcallsforthe v1/registration/ endpointcanbefoundhere.
GET/v2/registrations/Retrievesalldeviceregistrations.
Authentication: HTTP Basic app_uuid:api_key
Query Parameters:
Parameters Description
sizeControlsthemaximumnumberofregistrationstobereturned.Thisvaluedefaultsto20ifnotprovided.Valuesintherange0-50areaccepted.
page Controlswhichpageofresultswillbereturnedwithanoffsetofsizepage.Thisvaluedefaultsto1ifnotprovided.
qReturnsonlytheregistrationsresultscontainingthequerystringprovidedineitherthedeviceUuid,theregistrationtoken,thecustomuserid,orthedevicealias.
platform Returnsonlytheregistrationsresultsregisteredtothegivenplatform.Validinputsareall,ios,android,windows8,andbb10.
platformUuid ReturnsonlytheregistrationsresultsregisteredtothegivenplatformUuid.
topic Returnsonlytheregistrationsresultsregisteredtothegiventopicname.
ResponseData,status:200(OK)
{"registrations":[{"os":"",#oneof[ios|android|windowsPhone|windows8]"os_version":"",#deviceversionstring"device_model":"",#devicemodelidentifier"device_manufacturer":"",#devicemanufactureridentifier"device_alias":"",#applicationspecificdevice/useridentifier"device_uuid":"",#uniquedeviceidentifier"registration_token":"",#tokenprovidedbyAPNS(ios),GCM(android),MPNS(windowsPhone),orWNS(windows8)"active":""#canthedevicebetargetedforpushes}]"totalRegistrations":1#thetotalnumberofdeviceregistrationsforallpages"totalPages":1#thenumberofpagesofdeviceregistrations"page":1#thepageofresultsrequested"size":1#thesizeofthepageofresultsrequested}
©CopyrightPivotalSoftwareInc,2013-2018 71of98 1.6
TopicsATopic(formerlyaTag )isakeywordthatuserscansubscribetoinordertoreceivepushessenttothesametopic.Thetopicsthemselvesarefree-form,thatis,yourappdefinesthemasneededandtheycanbeanytextthatyourappneeds.
GET/v2/topicsReturnsallnon-expiredtopics.
Authentication: HTTP Basic app_uuid:api_key
Query Parameters:
Parameter Description
q:string Optional—Matchalltopicsthatcontainthestring.Defaultmatchallnon-expiredtopics.
size:integer
Optional—Maximumnumberoftopicstoreturn.Rangebetween1and50.Defaultsetto20.
page:integer
Optional—Pagenumbertoreturnsetoftopics.Defaultsetto1.
hasExpiry:boolean
Optional—Ifsettotrue,filterresultstotopicsthathaveanexpiry.Iffalse,filterresultstotopicswithnoexpiry.Ifmissing,nofilteringisdone,allresultingtopicsarereturned.Defaultreturnsallresultingtopics.
ResponseData,status:200(OK)Returnsajsonlistoftopics.
Forexample:
{"topics":list,//Listoftopicobjectsthatmatchtherequest"totalTopics":integer,//Totalnumberoftopicsthatmatchtherequest"totalPages":integer,//Totalnumberofpagesoftopicresults"page":integer,//Currentpagereturned.Sameaspageinrequest"size":integer,//Currentsizeofpage.Sameassizeinrequest}
//TopicObject
{"id":integer,//UniqueIDofthetopic"name":string,//Topicname"expireAt":long//Optional-Epochtime,inms,ofwhentopicwillexpire.Ifmissing,topicwillnotexpire.}
POST/v2/topics/Createsatopic,ifnotalreadycreated,withanoptionalexpirytime.
Authentication: HTTP Basic app_uuid:api_key
Query Parameters: None
RequestBody:
©CopyrightPivotalSoftwareInc,2013-2018 72of98 1.6
{"name":string,//Nameofthetopictocreate"expireAt":long,//Optional-Expirytimeofthetopic,inUnixepochtimeinms"timeToLive":long//Optional-Duration,inseconds,beforeexpiringthetopic.Mustbeatleast60seconds.}
Response:status:201(CREATED)
{"id":integer,//UniqueIDofthetopic"name":string,//Topicname"expireAt":long,//Optional-Epochtime,inms,ofwhentopicwillexpire.Ifmissing,topicwillnotexpire.}
DELETE/v2/topics/:topicIdDeletesanon-expiredtopic,definedbyitstopicID.
Authentication: HTTP Basic app_uuid:api_key
Query Parameters: None
RequestBody:None.
ResponseData,status:204(NOCONTENT)
POST/v2/topics/batch/Createsmultipletopicsinonebatch.
Authentication: HTTP Basic app_uuid:api_key
Query Parameters: None.
RequestBody:
{"topics":list,//Listoftopicobjectstocreate.Maximumsizeis1024"returnTopics":boolean//Optional-Iftrue,theresponsewillreturnthelistofcreatedtopics.Iffalse,onlythecountwillbereturned.Defaultstofalse.}
//Topicobject
{"name":string,//Nameofthetopictocreate"expireAt":long,//Optional-Expirytimeofthetopic,inUnixepochtimeinms"timeToLive":long//Optional-Duration,inseconds,beforeexpiringthetopic.Mustbeatleast60seconds.}
Note:EitherexpireAtortimeToLovemaybepresent,notboth.IfbothexpireAtandtimeToLivearemissing,thenthetopicwillneverexpire.
©CopyrightPivotalSoftwareInc,2013-2018 73of98 1.6
Response:status:201(CREATED)
{"numTopicsCreated":integer,//Numberofnewlycreatedtopics"numTopicsExisted":integer,//Numberoftopicsthatalreadyexistedfromrequests."topics":list//Listoftopicsadded.Notpresentif"returnTopics"intherequestisfalse.}
//TopicObject
{"id":integer,//UniqueIDofthetopic"name":string,//Topicname"expireAt":long//Optional-Epochtime,inms,ofwhentopicwillexpire.Ifmissing,topicwillnotexpire.}
DELETE/v2/topics/batchDeletemultipletopicsinonebatch.
Authentication: HTTP Basic app_uuid:api_key
Query Parameters: None.
RequestBody:
{"topicIds":list//Listoftopicids(integer)}
Response:status:200(OK)
{"numTopicsDeleted":integer//Numberoftopicsdeleted}
Note:EitherexpireAtortimeToLivemaybepresent,notboth.IfbothexpireAtandtimeToLivearemissing,thenthetopicwillneverexpire.
©CopyrightPivotalSoftwareInc,2013-2018 74of98 1.6
Custom User IDsTheCustomUserIDfeatureallowsyoutoregisteradeviceunderanIDthatismeaningfultoyoursystemsuchastheirlogin.Inaddition,thesameCustomUserIDcanbeusedtorefertomultipledevices.ThismeansthatapushsenttotheCustomUserIDwillbesentsimultaneouslytoalldevicesregisteredwiththisCustomUserID.
Note:TheCustomUserIDfieldiscasesensitivefordeviceregistrations.
CustomUserIDandTopicsCustomUserIDworksincombinationwithtopicssothatyoucantargetasetofCustomUserIDsaswellastopicsandthePushNotificationServicewillensurethatalldevicesreceiveonly1copyofthenotification.
GET/v2/custom_user_idsGetalistofCustomUserIDs
Authentication: HTTP Basic app_uuid:api_key
Query Parameters: None
ResponseBody:
{"custom_user_ids":["string1","string2"]}
Examples:RetrivealistofallCustomUserIDs:
{"custom_user_ids":["custom-user-id1"]}
GET/v2/custom_user_ids?q={query}GetCustomUserIDsbyQueryParameter
Authentication: HTTP Basic app_uuid:api_key
Query Parameters:
Parameter Description
q ReturnsonlytheCustomUserIDsresultscontainingthequerystringprovided.
ResponseBody:
©CopyrightPivotalSoftwareInc,2013-2018 75of98 1.6
{"custom_user_ids":["string1","string2"]}
Examples:RetriveCustomUserIDsbyqueryparameter(i.e.queryparameteris‘id1’):
{"custom_user_ids":["custom-user-id1"]}
Note:InordertousetheCustomUserIDsfeature,youwillhavetoregisteradeviceusingthePOSTmethodon /v1/registration endpoint,withacustom_user_id fieldpopulatedasdescribedinRegistersectionoftheRegistrationAPI.
{..."custom_user_id":"custom-user-id1"...}
ForadditionalinformationregardingRegistration,pleaseconsulttheRegistrationAPIsectionofourAPI.
©CopyrightPivotalSoftwareInc,2013-2018 76of98 1.6
ScheduleThisdocumentdecscibestheendpointsformanagingscheduledpushes.
Pushescanbescheduledfordeliveryinthefuturebyprovidingthescheduleinformationinthe/v1/pushPOSTAPI.Thesepushesreturnaschedule_idfieldthatcanbeusedastheidentifyforthe/v1/scheduleAPIsthataredescibedbelow.
GET/v1/schedulesGetallscheduledpushesforanapplication.
Authentication: HTTP Basic app_uuid:api_key
Query Parameters: None
RequestBody:None.
ResponseData,status:200(OK)
©CopyrightPivotalSoftwareInc,2013-2018 77of98 1.6
[{"schedule_id":"fc226fbc1443ebfe","scheduled_for":1423513994000,#EpochTimestampinmilliseconds"push":{"scheduleAt":1423513994000,#EpochTimestampinmilliseconds"scheduleIn":0,"expiryTime":null,"message":{"custom":{"windows8":{"options":"object","template_name":"","template_fields":"object","type":""},"windowsPhone":{"template_fields":"object","template":""},"ios":{"alert":{"body":"",#Thebodyofthepushmessage(overridesbodydefinedabove)"action-loc-key":"","loc-key":"","loc-args":["arg1","arg2",...],"title":"","title-loc-key":"","title-loc-args":["arg1","arg2",...],"launch-image":""},"category":"","badge":0,"sound":"","content-available":false,"extra":{}},"bb10":"","android":"object"},"body":""},"target":{"topics":["topic1","topics2",...],"platforms":["platform1","platform2",...],"devices":["device_uuid1","device_uuid2",...],"interactive-only":false,"platform":"",}}}]
GET/v1/schedules/:schedule_idGetasinglescheduledpushforanapplication.
Authentication: HTTP Basic app_uuid:api_key
Query Parameters: None
RequestBody:None.
ResponseData,status:200(OK)
©CopyrightPivotalSoftwareInc,2013-2018 78of98 1.6
{"schedule_id":"fc226fbc1443ebfe","scheduled_for":1423513994000,#EpochTimestampinmilliseconds"push":{"scheduleAt":1423513994000,#EpochTimestampinmilliseconds"scheduleIn":0,"expiryTime":null,"message":{"custom":{"windows8":{"options":"object","template_name":"","template_fields":"object","type":""},"windowsPhone":{"template_fields":"object","template":""},"ios":{"extra":"object","category":"","badge":0,"sound":"","content-available":false,"alert":{"body":"","loc-key":"","action-loc-key":"","loc-args":["arg1","arg2",...],"launch-image":""}},"bb10":"","android":"object"},"body":""},"target":{"interactive-only":false,"platform":"","topics":["topic1","topic2",...],"platforms":["platform1","platform2",...],"devices":["device_uuid1","device_uuid2",...]}}}
PUT/v1/schedules/:schedule_idUpdateascheduledpushforanapplication.
Authentication: HTTP Basic app_uuid:api_key
Query Parameters: None
RequestBody:
{"scheduleAt":1345852800000,#Epochtimestampinmilliseconds."message":{"custom":{"android":"object"},"body":""},"target":{"interactive-only":false,"platform":"","platforms":["platform1","platform2",...],"topics":["topic1","topic2",...],"devices":["device_uuid1","device_uuid2",...]}}
©CopyrightPivotalSoftwareInc,2013-2018 79of98 1.6
ResponseData,status:200(OK)
{"schedule_id":"fc226fbc1443ebfe","scheduled_for":1345852800000,#EpochTimestampinmilliseconds"push":{"scheduleAt":1345852800000,"scheduleIn":0,"expiryTime":null,"message":{"custom":{"windows8":{"options":"object","template_name":"","template_fields":"object","type":""},"windowsPhone":{"template_fields":"object","template":""},"ios":{"extra":"object","category":"","badge":0,"sound":"","content-available":false,"alert":{"body":"","loc-key":"","action-loc-key":"","loc-args":["arg1","arg2",...],"launch-image":""}},"bb10":"","android":"object"},"body":""},"target":{"interactive-only":false,"platform":"","platforms":["platform1","platform2",...],"topics":["topic1","topic2",...],"devices":["device_uuid1","device_uuid2",...]}}}
DELETE/v1/schedules/:schedule_idCancelascheduledpushforanapplication.
Authentication: HTTP Basic app_uuid:api_key
Query Parameters: None
RequestBody:None.
ResponseData,status:204(NOCONTENT)
©CopyrightPivotalSoftwareInc,2013-2018 80of98 1.6
Geofences
EndpointsforManagingGeofences
CreateGeofence
POST/v1/geofence
Createageofenceforanapp
Authentication: HTTP basic application_uuid:api_key
Query Parameters: None
RequestBody:
{"tags":["tag1","tag2"],"locations":["1","2"],"trigger_type":"enter","start_time":0,"expiry_time":1424443201000,"platform":"","data":{"ios":{"alertBody":"","category":"","alertAction":"","alertTitle":"","alertLaunchImage":"","hasAction":false,"applicationBadgeNumber":0,"soundName":"","userInfo":"object"},"android":"object"}}
GeofenceFieldstags
type:arrayofstrings
required:no
Thisisalistoftagstotarget.Ifnotemptyitwilllimittheaudienceforthegeofencetoonlyusersthathavesubcribedtooneormoreofthelistedtags
locations
required:yes
type:arrayofnumbers
Listoflocationidsforthelocationsthatshouldbeincludedinthegeofence
trigger_type
©CopyrightPivotalSoftwareInc,2013-2018 81of98 1.6
required:yes
type:“string”;possiblevaluesare“enter”,“exit”
Whentrigger_typeissetto“enter”thenotificationwillbedisplayedwhenauserenterthegeofence.Whenitissetto“exit”thenotificationwillnotbedisplayeduntiltheuserexitsthegeofence.
start_time
required:yes
type:millisecondtimestamp(integer)
Geofencesareonlyactiveforafixedperiodoftime.“start_time”determineswhenthegeofenceshouldbecomeactive.Setthisto“0”toactivatethegeofenceuponcreation
expiry_time
required:yes
type:millisecondtimestamp(integer)
Setsthetimewhenthegeofenceshouldbecomeinactive.
platform
required:yes
type:string;possiblevaluesare“android”,“ios”,“all”
Targetthegeofencetodevicesofaspecificplatform
data
required:yes
type:object
Thedataobjectcontainsplatformspecificfieldsforconstructingthenotificationtobedisplayed.Theseareslightlydifferentthanfieldsusedinthepushapibecausegeofencenotificationsareactuallylocalnotifications.CustomUserIDsarenotasupportedwaytotargetregistereddevicesforgeofences.
iOSGeofenceDataFields
ForApple’sreferenceonlocalnotificationsseehttps://developer.apple.com/library/ios/documentation/iPhone/Reference/UILocalNotification_Class/index.html#//apple_ref/occ/instp/UILocalNotification/alertBody
Allfieldshereareoptional.
alertBody
type:string
Astringorlocalized-stringkeytouseasthenotificationalertmessage.Ifniloremptytherenoalertwillbeshown.Printfstyleescapecharactersarestrippedfromthestringpriortodisplay;toincludeapercentsymbol(%)inthemessage,usetwopercentsymbols(%%).
categorytype:string
ThevalueofthispropertyisthecategorynameassociatedwitharegisteredUIUserNotificationSettingsobject.Whenthealertforthelocalnotificationisdisplayed,thesystemusesthestringyouspecifytolookupthegroupandretrieveitsactions.Itthenaddsabuttontothealertforeachactiondefinedbythegroup.Whentheusertapsoneofthosebuttons,theappiswokenup(orlaunched)andgivenachancetoperformthedesignatedaction.Ifthespecifiedcategorynamedoesnotbelongtoaregisteredgroupofactions,thealertdoesnotdisplayanyadditionalactionbuttons.
alertAction
type:string
©CopyrightPivotalSoftwareInc,2013-2018 82of98 1.6
Astringorlocalized-stringkeytouseasthetitleoftherightbuttonofthealertorthevalueoftheunlockslider,wherethevaluereplaces“unlock”in“slidetounlock”.Ifyouspecifynil,andalertBodyisnon-nil,“View”(localizedtothepreferredlanguage)isusedasthedefaultvalue.
alertTitle
type:string
Ashortdescriptionofthereasonforthealert.AppleWatchdisplaysthetitlestringaspartoftheshortlooknotificationinterface,whichhaslimitedspace.
alertLaunchImage
type:string
Identifiestheimageusedasthelaunchimagewhentheusertaps(orslides)theactionbutton(orslider).
hasActiontype:booleanDetermineswhetherornottoshowanalertaction.
applicationBadgeNumber
type:number
Thenumbertodisplayastheappicon’sbadge.Defaultvalueis0whichwillsimplynotdisplayabadge.
soundName
type:string
Thenameofthefilecontainingthesoundtoplaywhenanalertisdisplayed.
userInfo
type:dictionaryAdictionaryforpassingcustominformationtothenotifiedapp.
Response:
{"id":0,"tags":[""],"expiry_time":0,"trigger_type":"","locations":[{"name":"","id":0,"long":"","rad":0,"lat":"","created_at":0,"updated_at":0}],"platform":"","created_at":0,"updated_at":0,"data":{"ios":{"alertBody":"","category":"","alertAction":"","alertTitle":"","alertLaunchImage":"","hasAction":false,"applicationBadgeNumber":0,"soundName":"","userInfo":"object"},"android":"object"},"start_time":0}
©CopyrightPivotalSoftwareInc,2013-2018 83of98 1.6
GetGeofences
GET/v1/geofence
Getallgeofencesforanapp
Authentication: HTTP basic application_uuid:api_key
Query Parameters:
Parameters Description
page:integer resultpagetodisplay
size:integer numberofresultsperpage
timestamp:long timestampinmilliseconds
RequestBody:None
Response:
{"size":25,"totalGeofences":1,"totalPages":1,"page":1,"geofences":[{"id":1,"expiry_time":1424443201000,"trigger_type":"enter","updated_at":1423513994000,"created_at":1423513994000,"data":{"object":{"key":"value"}},"tags":["tag1"],"locations":[{"name":"sample","id":1,"lat":"0.0","long":"0.0","rad":100,"updated_at":1423513994000,"created_at":1423513994000}]}]}
GetGeofenceUpdates
GET/v1/geofences
Getupdatedgeofencessinceatimestamp.Thisendpointisusedbydevicestofetchanupdatedlistofgeofencestomonitor.
Authentication: HTTP basic platform_uuid:platform_secret
Query Parameters:
Parameters Description
timestamp:long timestampinmilliseconds
©CopyrightPivotalSoftwareInc,2013-2018 84of98 1.6
RequestBody:
None.
Response:
{"num":3,"deleted_geofence_ids":[1,2],"geofences":[{"id":5,"expiry_time":1424443201000,"trigger_type":"enter","updated_at":1423513994000,"created_at":1423513994000,"data":{"object":{"key":"value"}},"tags":["tag1"],"locations":[{"name":"sample","id":1,"lat":"0.0","long":"0.0","rad":100,"updated_at":1423513994000,"created_at":1423513994000}],"last_modified":1423513994000}
deleted_geofence_ids
type:arrayofnumbers
Listofidsforgeofencesthathavebeendeletedsincetherequestedtimestamp.
geofences
type:arrayofgeofenceobjects
Listofgeofencesthathavebeenaddedsincetherequestedtimestamp.
GetOneGeofence
GET/v1/geofence/:geofence_id
Authentication: HTTP basic application_uuid:api_key
Query Parameters: None
RequestBody:
None.
Response:
©CopyrightPivotalSoftwareInc,2013-2018 85of98 1.6
{"id":1,"expiry_time":1424443201000,"trigger_type":"enter","updated_at":1423513994000,"created_at":1423513994000,"data":{"object":{"key":"value"}},"tags":["tag1"],"locations":[{"name":"sample","id":1,"lat":"0.0","long":"0.0","rad":100,"updated_at":1423513994000,"created_at":1423513994000}]}
UpdateaGeofence
PUT/v1/geofence/:geofence_id
Authentication: HTTP basic application_uuid:api_key
Query Parameters: None
RequestBody:
{"trigger_type":"enter","expiry_time":1424443201000,"data":{"object":{"key":"value"}},"tags":["tag1"],"locations":[1]}
Response:
{"id":1,"expiry_time":1424443201000,"trigger_type":"enter","updated_at":1423513994000,"created_at":1423513994000,"data":{"object":{"key":"value"}},"tags":["tag1"],"locations":[{"name":"sample","id":1,"lat":"0.0","long":"0.0","rad":100,"updated_at":1423513994000,"created_at":1423513994000}]}
©CopyrightPivotalSoftwareInc,2013-2018 86of98 1.6
DeleteaGeofence
DELETE/v1/geofence/:geofence_id
Authentication: HTTP basic application_uuid:api_key
Query Parameters: None
RequestBody:
None.
Response:204(NOCONTENT)
Locations
Endpointsformanaginggeofencelocations.
GetAllLocations
GET/v1/locations
Getallgeofencelocationsforanapp
Authentication: HTTP basic application_uuid:api_key
Query Parameters:
Parameters Description
page:integer resultpagetodisplay
size:integer numberofresultsperpage
timestamp:long timestampinmilliseconds
q:string keywordtosearchfor
RequestBody:
None.
Response:
©CopyrightPivotalSoftwareInc,2013-2018 87of98 1.6
{"size":25,"locations":[{"name":"sample","id":1,"long":"0.0","rad":100,"lat":"0.0","created_at":1423513994000,"updated_at":1423513994000}],"totalLocations":1,"totalPages":1,"page":1}
GetOneLocation
GET/v1/locations/:location_id
Authentication: HTTP basic application_uuid:api_key
Query Parameters: None
RequestBody:
None.
Response:
{"name":"sample","id":1,"lat":"0.0","long":"0.0","rad":100,"updated_at":1423513994000,"created_at":1423513994000}
CreateaNewLocation
POST/v1/locations
Authentication: HTTP basic application_uuid:api_key
Query Parameters: None
RequestBody:
{"name":"sample","lat":"0.0","long":"0.0","rad":100}
©CopyrightPivotalSoftwareInc,2013-2018 88of98 1.6
name:anameforthelocation
lat:latitudeindegrees
long:longitudeindegrees
rad:radiusinmeters
Response:
{"name":"sample","id":1,"lat":"0.0","long":"0.0","rad":100,"updated_at":14235139940000,"created_at":1423513994000}
UpdateaLocation
PUT/v1/locations/:location_id
Authentication: HTTP basic application_uuid:api_key
Query Parameters: None
RequestBody:
{"name":"sample","lat":"0.0","long":"0.0","rad":100}
Response:
{"name":"sample","id":1,"lat":"0.0","long":"0.0","rad":100,"updated_at":1423513994000,"created_at":1423513994000}
DeleteaLocation
DELETE/v1/locations/:location_id
Authentication: HTTP basic application_uuid:api_key
Query Parameters: None
©CopyrightPivotalSoftwareInc,2013-2018 89of98 1.6
RequestBody:
None.
Response:204(NOCONTENT)
LocationGroups
Endpointsformanaginggeofencelocations.
GetAllLocationGroups
GET/v1/location_groups
Getalllocationgroupsforanapp
Authentication: HTTP basic application_uuid:api_key
Query Parameters:
Parameters Description
page:integer resultpagetodisplay
size:integer numberofresultsperpage
timestamp:long timestampinmilliseconds
q:string keywordtosearchfor
RequestBody:
None.
Response:
{"size":25,"location_groups":[{"name":"samplegroup","id":1,"description":"samplelocationgroup","locations":[{"name":"sample","id":1,"long":"0.0","rad":100,"lat":"0.0","createdAt":1423513994000,"updatedAt":1423513994000}],"created_at":1423513994000,"updated_at":1423513994000}],"totalLocationGroups":1,"totalPages":1,"page":1}
©CopyrightPivotalSoftwareInc,2013-2018 90of98 1.6
GetOneLocationGroup
GET/v1/location_groups/:location_group_id
Authentication: HTTP basic application_uuid:api_key
Query Parameters: None
RequestBody:
None.
Response:
{"name":"samplegroup","id":1,"description":"samplelocationgroup","locations":[{"name":"samplelocation","id":1,"long":"0.0","lat":"0.0","rad":100"createdAt":1423513994000,"updatedAt":1423513994000}],"created_at":1423513994000,"updated_at":1423513994000}
CreateaLocationGroup
POST/v1/location_groups
Authentication: HTTP basic application_uuid:api_key
Query Parameters: None
RequestBody:
{"name":"samplegroup","location_ids":[1],"description":"asamplelocationgroup"}
name:nameforthelocationgroup
location_ids:listofidsforlocationstoincludeinthegroup
description:ashortdescriptionofthegroup
Response:
©CopyrightPivotalSoftwareInc,2013-2018 91of98 1.6
{"name":"samplegroup","id":1,"description":"","locations":[{"name":"sample","id":1,"long":"0.0","rad":100,"lat":"0.0","createdAt":1423513994000,"updatedAt":1423513994000}],"created_at":1423513994000,"updated_at":1423513994000}
UpdateaLocationGroup
PUT/v1/location_groups/:location_group_id
Authentication: HTTP basic application_uuid:api_key
Query Parameters: None
RequestBody:
{"name":"samplegroup","location_ids":[1],"description":"asamplelocationgroup"}
Response:
{"name":"samplegroup","id":1,"description":"","locations":[{"name":"sample","id":1,"long":"0.0","rad":100,"lat":"0.0","createdAt":1423513994000,"updatedAt":1423513994000}],"created_at":1423513994000,"updated_at":1423513994000}
DeleteaLocationGroup
DELETE/v1/location_groups/:location_group_id
©CopyrightPivotalSoftwareInc,2013-2018 92of98 1.6
Authentication: HTTP basic application_uuid:api_key
Query Parameters: None
RequestBody:
None.
Response:204(NOCONTENT)
©CopyrightPivotalSoftwareInc,2013-2018 93of98 1.6
Push Notification Service Release Notes
v1.6.3Release Date: September 2016
Updatedstemcelltov3263toaddresskernelvulnerabilities(includes4.4kernel)
v1.6.2Release Date: September 2016
Updatedstemcelltov3263toaddresskernelvulnerabilities(includes4.4kernel)
Fixes:
FixeddashboardissuefoundwhenupgradingfromPCFv1.7toPCFv1.8
Known Issues
IfyouinstalledPushv1.6.2+afterupgradingtoPCFv1.8,thenremovetheappnamed push-notifications-analytics withthefollowingcommand:
$cfdeletepush-notifications-analytics
v1.6.1Release Date: August 2016
Features:
ProxysupportinPushTile:UserscannowaddaproxyinthePushTile(viaOpsMgrconsole)
InstallationlogsnowavailableinOpsMgrconsoleuponinstallationfailurefixes
Fixes:
Fixedissuewithmultipletenantsbeingprovisionedinsystemorginpushnotificationsspace
Fixedscalingissuewithpushapiinstancesduetolackofdatabaseconnections
Known Issues:
UpgradingtoPCFv1.8exposesabuginversionsofPushv1.6.1andolder.Theimpactisthatthedashboardwon’tbeabletodisplayanalytics(amessagewillappearstating“AnalyticsDataisnotavailableatthemoment”).Analyticsdataisstillcollectedonthebackend,thebugpreventsitfrombeingdisplayed.
The recommended solution is to upgrade to push v1.6.2 prior to upgrading to PCF v1.8 (this is now a pre-requisite for PCF v1.8)
Ifinstallingpushv1.6.1orearlieronPCFv1.8,followtheinstructionsbelow
1. Toconfirmthisistheproblemyouareexperiencing,youcanchecktoseeifthereisaCFapprunninginthe system organd push-notifications spacecalled push-notifications-analytics .
2. Replace push-analytics with push-notifications-analytics andaddamatchingrouteasperthecommandsshownbelow
cfdeletepush-analyticscfrenamepush-notifications-analyticspush-analyticscfmap-routepush-analytics$ENV_URL--hostnamepush-analytics
Note:UpdatetoPushNotificationServicev1.6.2priortoupgradingtoPivotalCloudFoundryv1.8.
©CopyrightPivotalSoftwareInc,2013-2018 94of98 1.6
where $ENV_URL isthevalueofthedomainnameusedforyourPCFenvironment
v1.6.0Release Date: July 2016
DevicescanbegroupedunderCustomUserIDswhichcanbetargetedforpushes
TagshavebeenreplacedbyTopics
Topicscanbecreatedwithexpirydates
1.5.7Release Date: December 2016
SecurityreleaseforCVEasdetailedinUSN-3156-1
1.5.6Release Date: December 2016
SecurityreleaseforCVEasdetailedinUSN-3151-2
v1.5.3Release Date: June 2016
BugfixforServicebrokerbugwithHTTPS
v1.5.0Release Date: June 2016
NewHeartbeatApplicationisdeployedwiththePushNotificationsService
HeartbeatMonitorAppavailableoniOSandAndroid
v1.4.27Release Date October 2016
Bumptostemcellv3151.3forCVEasdetailedinUSN-3106-2:https://www.ubuntu.com/usn/usn-3106-2/
v1.4.25Release Date October 2016
BumpUbuntustemcellforUSN-3099-2:Linuxkernel(XenialHWE)vulnerabilities
v1.4.24Release Date: October 2016
©CopyrightPivotalSoftwareInc,2013-2018 95of98 1.6
UpdatedUbuntustemcellforUSN-3087-2:OpenSSLregression
v1.4.12Release Date: June 2016
UpdatedBOSHstemcelltov3262.2
BugfixforcfCLI
v1.4.10Release Date: June 2016
Securityreleaserequiringstemcellv3232.8
v1.4.9Release Date: June 2016
Securityreleaserequiringstemcellv3232.6
BugfixforServicebrokerbugwithHTTPS
v1.4.7Release Date: May 2016-Securityreleaserequiringstemcellv3232.2
v1.4.5Release Date: May 2016-PCFv1.7compatibility.-Updatetothisversionofpush updatingtoPCFv1.7.0
v1.4.3Release Date: March 2016-Securityreleaserequiringstemcellv3146.10.
v1.4.2Release Date: February 2016-Securityreleaserequiringstemcellv3146.8.
v1.4.0Release Date: November 2015
ThePushNotificationsServicenowsupportsmultipletenants.
PushNotificationsisnowaservicethatcanbeprovisionedfromtheCFMarketplace.ThedashboardnowrequiresaTenantId.
Thedashboardnowdisplayslogsrelatedtopushactivities.
TheanalyticssystemnowconfiguresasecondRedistobehaveasacacheforstoringlogs.
UpdatetothePushSDKsupportsiOS9andincludesaSwiftsampleapp.
©CopyrightPivotalSoftwareInc,2013-2018 96of98 1.6
ThePushSDKforAndroidnowsupportsAndroid6.0Marshmallow,includingthenewpermissionssystem.
SeethePushSampleappforanexampleofAndroid6.0Marshmallowpermissions.
v1.3.5Release Date: October 2015
SupportforPCFv1.6andDiego.
SOCKSproxybugfix.
v1.3.4Release Date: October 2015
Bugfixesforsmoketests.
v1.3.3Release Date: September 2015
Bugfixesforcertainscenariosregardingexpirytime.
v1.3.3iOSandAndroidClientSDKPushappanalytics.
CustomHTTPrequestheaders.
CustomSSLauthentication.
v1.3.2Release Date: August 2015
Deprecatedlucid64stackinfavourofthenewTrusty/cflinuxfs2stack
ProxySupportforiOSpushnotifications.SupportsSOCKSproxies.
ProxySupportforAndroidpushnotifications.SupportsHTTPandSOCKSproxies.
v1.3.2iOSandAndroidClientSDKEnableanddisablegeofencesatruntime.
AddedamethodtoreadthedeviceUUIDatruntime.
v1.3.1Release Date: August 2015
SupportforRabbitMQServiceversionsv1.4.0andlater
Tagmanagementaddedtodashboard
Abilitytoregeneratepushapikeys
©CopyrightPivotalSoftwareInc,2013-2018 97of98 1.6
Minorimprovementstoinstallation
Allowcertificatecheckstobedisabledincfenvironmentsthatuseselfsignedcertificates
v1.3.1iOSandAndroidClientSDKSSLCertificatepinning.
Anygeofenceswithtagswillbemonitoredonlyiftheuserissubscribedtothattag.
v1.3.0Release Date: June 2015
Locationbasednotifications
AndroidandiOSsupport(SDKs)
Dashboardsupport
MapsSavedlocationsandgroupsoflocationsActivegeofencesview
Upgradingfromversionv1.2.xtov1.3.0
v1.2.1Release Date: April 2015
Offlineinstallationsupport
v1.2.0Release Date: March 2015
Scheduledpushnotifications
Notificationswithexpirytime
UpdatedUI/UXfordashboard(sendingscheduledpushwithexpirytime)
v1.1.0-January2015
v1.0.1-November2014
v1.0.0—July2014
©CopyrightPivotalSoftwareInc,2013-2018 98of98 1.6