table of contents · device-specific service parameters. client sdks for ios and android provide a...

117
1 2 4 9 12 24 27 37 40 41 42 42 42 42 43 43 44 44 44 45 45 46 46 46 46 46 47 47 47 49 63 73 76 77 78 86 89 90 93 95 99 112 Table of Contents Table of Contents Push Notification Service for Pivotal Cloud Foundry Installation DevOps Configuring Heartbeat Monitor for iOS Configuring Heartbeat Monitor for Android Using the Dashboard V1.7.0 Push Notifications ASG Installation Network Setup Guide Development Guide First Push Walkthrough Step 1 Step 2 Step 3 Step 4 Step 5 Step 6 Step 7 Step 8 Step 9 Step 10 Geofence Walkthrough Step 1 Step 2 Step 3 Step 4 Step 5 Step 6 Step 7 iOS Push Client SDK Android Push Client SDK Setting up Push Notifications with FCM Windows Phone 8.1 Push Client SDK APIs Push Registration Registrations Topics Custom User IDs Schedule Geofences Push Notification Service Release Notes © Copyright Pivotal Software Inc, 2013-2018 1 of 117 1.7

Upload: others

Post on 01-Feb-2021

0 views

Category:

Documents


0 download

TRANSCRIPT

  • 1249

    12242737404142424242434344444445454646464646474747496373767778868990939599

    112

    TableofContents

    TableofContentsPushNotificationServiceforPivotalCloudFoundryInstallationDevOpsConfiguringHeartbeatMonitorforiOSConfiguringHeartbeatMonitorforAndroidUsingtheDashboardV1.7.0PushNotificationsASGInstallationNetworkSetupGuideDevelopmentGuideFirstPushWalkthroughStep1Step2Step3Step4Step5Step6Step7Step8Step9Step10GeofenceWalkthroughStep1Step2Step3Step4Step5Step6Step7iOSPushClientSDKAndroidPushClientSDKSettingupPushNotificationswithFCMWindowsPhone8.1PushClientSDKAPIsPushRegistrationRegistrationsTopicsCustomUserIDsScheduleGeofencesPushNotificationServiceReleaseNotes

    ©CopyrightPivotalSoftwareInc,2013-2018 1of117 1.7

  • Push Notification Service for Pivotal Cloud FoundryThisisdocumentationforthePushNotificationService forPivotalCloudFoundry (PCF).

    ProductSnapshotCurrentPushNotificationServiceforPCFDetails

    Version:v1.7.1Release Date:January2017SDK Versions:Androidv1.7.0,iOSv1.7.0Compatible Ops Manager Version(s):v1.7.8andlaterCompatible Elastic Runtime Version(s):v1.7.x,v1.8.x,v1.9.xvSphere support?YesAWS support?YesGCP support?Yes

    UpgradingtotheLatestVersion

    PleaseupgradetoPushv1.4.5+beforeupgradingtoPCFv1.7.1.

    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.7.1

    v1.8.x v1.4.5+ v1.7.1

    AboutThePivotalPushNotificationService forPivotalCloudFoundry allowsdeveloperstocreateamobilebackendthatcanbeusedtosendpushnotificationstomobileapps.TheserviceconnectsandmanagestheinterfacetoApplePushNotificationService,GoogleCloudMessaging,WindowsPushNotificationServices,andBlackBerryPushService.

    EachmobileappcommunicateswiththeserviceforregistrationsandnotificationpreferencesbyusingthecorrespondingclientSDK.Back-endbusinesslogicserverssendpushnotificationstoallusers,usersbyplatform,usersbygeolocation,oruserswithspecifiedtagsbysendingtherequesttotheappropriatePushNotificationServiceAPIendpoint.

    ©CopyrightPivotalSoftwareInc,2013-2018 2of117 1.7

    https://network.pivotal.io/products/push-notification-servicehttps://network.pivotal.io/products/pivotal-cfhttps://network.pivotal.io/products/push-notification-servicehttps://network.pivotal.io/products/pivotal-cf

  • Forinstallation,aPCFadministratorinitiallyimportsthePivotalPushNotificationspackageintoPCFOperationsManagerandconfiguresitviatheDashboardatwhichpointtheservicebecomesavailabletosendnotifications.TheDashboardprovidestheabilitytoconfigureapps,environments,anddevice-specificserviceparameters.ClientSDKsforiOSandAndroidprovideasimplifiedwaytointegratewiththePushNotificationsservice.WindowsPhone8,Windows8,andBlackberry10appscanalsousetheservice.

    ThePushNotificationsservicerequires:

    PivotalRabbitMQ

    Redisdatabase(PivotalRedisoruserprovided)

    MySQLdatabase(PivotalMySQLoruserprovided)

    ©CopyrightPivotalSoftwareInc,2013-2018 3of117 1.7

  • 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.

    Afteryouhavecompletedthisconfigurationclick“Save”.

    ©CopyrightPivotalSoftwareInc,2013-2018 4of117 1.7

    https://network.pivotal.io/products/p-mysqlhttps://network.pivotal.io/products/pivotal-rabbitmq-servicehttps://network.pivotal.io/products/p-redishttps://network.pivotal.io/products/pivotal-cfhttp://network.pivotal.io/http://docs.pivotal.io/pivotalcf/customizing/add-delete.htmlhttps://network.pivotal.io/products/p-mysqlhttp://docs.pivotal.io/p-mysql/#installationhttp://docs.pivotal.io/p-mysql/1-8/index.html#service-plan

  • 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 5of117 1.7

    https://network.pivotal.io/products/p-redishttp://docs.pivotal.io/redis/index.htmlhttp://redis.io/topics/cluster-spechttp://docs.pivotal.io/pivotalcf/customizing/managing_errands.htmlhttps://bosh.io/stemcells

  • 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 6of117 1.7

    https://github.com/cloudfoundry/cli

  • 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,whichthenshowstheappsandservicesrunningunderthatspace.

    ©CopyrightPivotalSoftwareInc,2013-2018 7of117 1.7

  • 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 8of117 1.7

  • 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.

    CertificatesgeneratedinElasticRuntimearesignedbytheOperationsManagerCertificateAuthority.Theyarenottechnicallyself-signed,buttheyarereferredtoas‘Self-SignedCertificates’intheOpsManagerGUIandthroughoutthisdocumentation.

    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 9of117 1.7

    http://docs.pivotal.io/push/1-7/troubleshooting.html

  • 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

    FollowtheseinstructionstobackupsolelythePushNotificationdatabase.

    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 10of117 1.7

    http://docs.pivotal.io/p-mysql/backup.html#automated-backupshttp://docs.pivotal.io/p-mysql/backup.html#manual-process

  • (i.e.:iOSpushcertificates,GoogleAPIkeys).Thisvalueissetatinstalltimeandshouldnotbemodified.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 11of117 1.7

    http://docs.pivotal.io/push/1-7/redis-backup.html

  • Configuring Heartbeat Monitor for iOSThistopicdescribeshowPivotalCloudFoundry(PCF)operatorscanconfigurethePushNotificationHeartbeatMonitorappforiOS.

    HeartbeatMonitorisaCloudFoundryappdeployedbythePCFPushNotificationservicetohelpyouensuretheservicerunscorrectlyend-to-end.Itdoesthisbysendingapush,orheartbeat,everyminutetothedevicesregisteredwiththeapp.YoucanalsoselecttheappinthePushdashboardtoviewitshistoricaldata.

    FollowtheinstructionsbelowtoconfigureHeartbeatMonitorandrunthecompanioniOSapponyourdevice.

    PrerequisitesToconfiguretheHeartbeatMonitorappforiOS,youmusthavethefollowing:

    AniOS8+device

    ThelatestXcodethatsupportsSwift2.2installedonyourworkstation

    AnAppleDeveloperaccount

    RequestaniOSDevelopmentCertificateFollowthesestepstoobtainaniOSdevelopmentcertificate:

    1. NavigatetotheCertificates, Identifiers & ProfilessectionoftheAppleDeveloperPortal .

    2. Inthesidenavigation,selectCertificates>All.

    3. Clickthe+buttoninthetoprighttoaddanewcertificate.

    4. SelectiOS App DevelopmentandclickContinue.

    ©CopyrightPivotalSoftwareInc,2013-2018 12of117 1.7

    https://developer.apple.com/account/ios/certificate

  • 5. Followtheon-screeninstructionstoCreate a CSR fileandclickContinue.

    6. Uploadthe .csr fileyoucreatedandclickContinuetogeneratethenewcertificate.

    7. ClickDownload.

    8. OpenyourcertificateandimportittotheKeychainAccessappwhenprompted.

    RequestanAPNSCertificateFollowthesestepstoenableyourapptoreceivepushnotifications:

    CreateanAppID

    ©CopyrightPivotalSoftwareInc,2013-2018 13of117 1.7

  • 1. NavigatetotheCertificates, Identifiers & ProfilessectionoftheAppleDeveloperPortal .

    2. Inthesidenavigation,selectIdentifiers>App IDs.

    3. Clickthe+buttontocreateanAppID.

    4. EnteranNameandaBundle ID.

    5. SelectthePush NotificationscheckboxandclickContinue.

    ©CopyrightPivotalSoftwareInc,2013-2018 14of117 1.7

    https://developer.apple.com/account/ios/certificate

  • 6. ClickRegister.

    CreateanAPNSCertificate1. IntheApp IDslist,selecttheAppIDyouregisteredandclickEdit.

    ©CopyrightPivotalSoftwareInc,2013-2018 15of117 1.7

  • 2. UnderthePush Notificationssection,chooseDevelopment SSL CertificateandclickthecorrespondingCreate Certificatebutton.

    3. Followtheon-screeninstructionstocreateanewCSR.

    4. Uploadthe .csr fileyoucreatedandclickContinuetogeneratethenewcertificate.

    5. ClickDownload.

    6. OpenyourcertificateandimportittoKeychainAccesswhenprompted.

    7. InKeychain Access,selectbothyourApple Development iOS Push Servicescertificateandtheprivatekeyitwassignedwith.

    ©CopyrightPivotalSoftwareInc,2013-2018 16of117 1.7

  • 8. RightclickyourselectionandchooseExport 2 Items…

    9. Savethe.p12fileforuploadingtothePushdashboardinalaterstep.

    CreateaProvisioningProfileFollowthesestepstocreateaProvisioningProfilethatyouspecifywhenbuildingtheHeartbeatMonitoriOSappinXcode:

    RegisteraDevice

    1. NavigatetotheCertificates, Identifiers & ProfilessectionoftheAppleDeveloperPortal .

    2. Inthesidenavigation,selectDevices>All.

    3. Clickonthe+buttoninthetoprighttoaddadevice.

    4. RetrievetheUDIDofyourdevice:

    a. Connectyourdevicetoyourcomputer.b. OpeniTunes.c. Selectthedevicetab.

    5. ClicktheSerial NumberofthedevicetorevealtheUDIDandrightclickthefieldtocopyit.

    Note:YouneedaniOS8+DevicetouseHeartbeatMonitor.IfyoualreadyhaveaniOS8+Deviceregistered,skiptothenextstep.

    ©CopyrightPivotalSoftwareInc,2013-2018 17of117 1.7

    https://developer.apple.com/account/ios/certificate

  • 6. IntheAppleDeveloperPortal,enteraNameforyourdeviceandpastetheUDIDintoitsfield.

    7. ClickRegister.

    CreateaProfile1. NavigatetotheCertificates, Identifiers & ProfilessectionoftheAppleDeveloperPortal .

    2. Inthesidenavigation,selectProvisioning Profiles>All.

    3. Clickonthe+buttoninthetoprighttocreateaProvisioningProfile.

    4. ChoosetheiOS App DevelopmenttypeandclickContinue.

    5. FromtheApp IDdropdown,selecttheAppIDyoucreatedearlierandclickContinue.

    6. SelecttheDeveloper Certificate(s)thatyouwanttouseandclickContinue.

    7. SelecttheDevicesthatyouregisteredandclickContinue.

    8. ProvideadescriptiveNamefortheProvisioningProfileandclickContinue.

    9. ClickDownloadandopenyourProvisioning Profile.

    Note:WhenyouopenyourProvisioningProfile,Xcodeinstallsitwithoutprovidinganyconfirmation.Inalaterstep,youconfigureyourXcodeappprojecttousethisProvisioningProfile.

    ©CopyrightPivotalSoftwareInc,2013-2018 18of117 1.7

    https://developer.apple.com/account/ios/certificate

  • ConfigureyourPushDashboardFollowthesestepstonavigatetothePushdashboardandthenconfiguretheservicetotalktoyourdevice.

    YoucannavigatetothePushdashboardusingeitherAppsManagerortheCloudFoundryCommandLineInterface(cfCLI).UsethecfCLIinstructionsifyoudidnotenablethePush Apps ManagererrandwhendeployingElasticRuntime.

    NavigatetoPushDashboardusingAppsManager1. Inabrowser,navigateto apps.YOUR-SYSTEM-DOMAIN .

    2. Selectthesystemorgandthepush-notificationsspace.

    3. ClicktheServicestab.

    4. SelectthePCF Push Notification ServicerowandclicktheManagelink.

    NavigatetoPushDashboardusingcfCLI1. Openaterminalwindowandlogin:

    $cflogin-ahttps://api.YOUR-SYSTEM-DOMAIN-uUSERNAME-pPASSWORD

    2. Targetthecorrectorgandspace:

    $cftarget-osystem-spush-notifications

    3. Runthefollowingcommand:

    $cfservicepush-service-instance

    4. CopytheURLfromtheDashboardfieldandpasteitintoyourbrowser.

    ConfigurethePushNotificationService1. SelecttheHeartbeat Appfromthelistofapplications.

    2. SelecttheConfigurationpane.

    ©CopyrightPivotalSoftwareInc,2013-2018 19of117 1.7

  • 3. UnderthePlatformssection,intheHeartbeat iOS Platformrow,clickthepencilicontoedittherecord.

    4. Completethefollowingfields:MODE:Select Development fromthedropdownmenu.CERTIFICATE:ClickChoose FileanduploadtheAPNScertificateyoucreated.PASSWORD:EnterthepasswordyouusedwhencreatingyourAPNScertificate.

    5. ClickSave.

    RuntheApponYourDeviceFollowthesestepstoopentheprojectfortheHeartbeatMonitoriOSappinXcodeandruntheapponyourdevice:

    DownloadtheAppRepo1. ClonethePushiOSHeartbeatMonitorrepository:

    [email protected]:cfmobile/push-ios-heartbeatmonitor.git

    2. RunthefollowingcommandtoopentheXcodeproject:

    $openPCF\Push\Heartbeat\Monitor.xcodeproj/

    ©CopyrightPivotalSoftwareInc,2013-2018 20of117 1.7

  • ConfiguretheAppProject1. IntheProjectNavigator,selectthe Pivotal.plist file.

    2. Intheeditor,changethevaluefor pivotal.push.serviceUrl tothePushNotificationAPIendpointforyourenvironment: https://push-api.YOUR-SYSTEM-DOMAIN .

    3. EnsurethatthevaluesforthefollowingRootfieldsintheeditormatchthecorrespondingvaluesinthePushdashboardundertheHeartbeat iOSPlatformrecord:

    Root Field in Editor Platform Field in Push Dashboard

    pivotal.push.platformUuidDevelopment Platform UUID

    pivotal.push.platformSecretDevelopment Platform Secret

    4. UndertheGeneraltab,settheProvisioning Profiledropdownstotheprofileyoucreatedearlier.

    Note:Donotselectthecheckboxtoautomaticallymanagesigning.

    ©CopyrightPivotalSoftwareInc,2013-2018 21of117 1.7

  • 5. UndertheCapabilitiestab,ensurethatbothStepsareenabledforPush Notifications.

    6. IfyourPCFdeploymentdoesnotuseanSSLcertificatesignedbyaCertificateAuthority(CA),addanexceptiondomaintothe info.plist filebyselectingApp Transport Security Settings>Exception Domainsandentering push-api.YOUR-SYSTEM-DOMAIN .

    BuildandRuntheApp1. AtthetopoftheXcodewindow,selectthedeviceiconandchooseyourdevice.

    2. Clicktheplaybuttontobuildandruntheapponyourdevice.

    3. SelectAllowwhentheappasksifitcansendyounotifications.

    ©CopyrightPivotalSoftwareInc,2013-2018 22of117 1.7

  • Thescreenupdateswithanewheartbeatcounteveryminuteasitreceivespushesfromyourenvironment.

    Note:IfyousendatestpushtoyourdevicefromthePushdashboard,ensuretheappisnotopenonyourdevice.Youcannotseethetestpushwhiletheappisopen.

    ©CopyrightPivotalSoftwareInc,2013-2018 23of117 1.7

  • Configuring Heartbeat Monitor for AndroidThistopicdescribeshowPivotalCloudFoundry(PCF)operatorscanconfigurethePushNotificationHeartbeatMonitorappforAndroid.

    HeartbeatMonitorisaCloudFoundryappdeployedbythePCFPushNotificationservicetohelpyouensuretheservicerunscorrectlyend-to-end.Itdoesthisbysendingapush,orheartbeat,everyminutetothedevicesregisteredwiththeapp.YoucanalsoselecttheappinthePushdashboardtoviewitshistoricaldata.

    FollowtheinstructionsbelowtoconfigureHeartbeatMonitorandrunthecompanionAndroidapponyourdevice.

    PrerequisitesTheproceduresinthisdocumentrequirethefollowing:

    YoumusthaveaccesstoaPCFenvironmentwiththePushNotificationServiceinstalled.

    YoumusthaveAndroidStudio2.2orlaterinstalledonyourmachine.

    YoumusthavetheGoogleRepositoryfromtheAndroidSDKManager .

    YoumusthavethePushAndroidSDK1.7orlaterfromGithub .

    ThedevicesthatyouwanttosendpushnotificationstomustrunAndroid2.3(Gingerbread)orlater.

    ThedevicesthatyouwanttosendpushnotificationstomusthaveGooglePlayServices9.8.0orlater.

    PrepareanFCMProjectFollowthesestepstoprepareanFCMprojectforyourapp.

    1. NavigatetotheFirebaseConsole andcreateanaccountifyoudonothaveonealready.

    2. Onceloggedin,CreateaprojectfortheHeartbeatMonitor.

    a. Whenprompted,clickAdd Firebase to your Android app.b. ForPackage name,enter io.pivotal.android.push.heartbeatmonitor .c. EnsuretheDebug signing certificate SHA-1matchestheSHA-1fromyourdebugsigningcertificate.Forinstructionsonhowtogetthis

    fingerprint,refertoAuthenticatingYourClient intheGoogleAPIsforAndroiddocumentation.d. Afteryoufinishcreatingorimportingyourproject,a google-services.json filedownloads.Keeptrackofthisfileforlateruse.

    3. Clickyourproject.

    4. ClickthesettingsiconnexttoyourprojectnameandselectProject Settings.

    5. SelecttheCloud Messagingtab.

    6. RecordtheServer keyforlateruse.

    ConfigureYourPushDashboardFollowthesestepstonavigatetothePushdashboardandthenconfiguretheservicetotalktoyourdevice.

    YoucannavigatetothePushdashboardusingeitherAppsManagerortheCloudFoundryCommandLineInterface(cfCLI).UsethecfCLIinstructionsifyoudidnotenablethePush Apps ManagererrandwhendeployingElasticRuntime.

    NavigatetoPushDashboardusingAppsManager1. Inabrowser,navigateto apps.YOUR-SYSTEM-DOMAIN .

    2. Selectthesystemorgandthepush-notificationsspace.

    3. ClicktheServicestab.

    ©CopyrightPivotalSoftwareInc,2013-2018 24of117 1.7

    https://developer.android.com/tools/help/sdk-manager.htmlhttps://github.com/cfmobile/push-androidhttps://console.firebase.google.com/https://developers.google.com/android/guides/client-auth

  • 4. SelectthePCF Push Notification ServicerowandclicktheManagelink.

    NavigatetoPushDashboardusingcfCLI1. Openaterminalwindowandlogin:

    $cflogin-ahttps://api.YOUR-SYSTEM-DOMAIN-uUSERNAME-pPASSWORD

    2. Targetthecorrectorgandspace:

    $cftarget-osystem-spush-notifications

    3. Runthefollowingcommand:

    $cfservicepush-service-instance

    4. CopytheURLfromtheDashboardfieldandpasteitintoyourbrowser.

    ConfigurethePushNotificationService1. SelecttheHeartbeat Appfromthelistofapplications.

    2. SelecttheConfigurationpane.

    3. UnderthePlatformssection,intheHeartbeat Android Platform over FCMrow,clickthepencilicontoedittherecord.

    4. IntheGoogle Keyfield,pastetheserverkeythatyourecordedearlier.

    RuntheApponYourDeviceFollowthesestepstocompileandruntheapponyourAndroiddevice.

    1. NavigatetothePushAndroidHeartbeatMonitor repository.

    2. Clonetherepositorytoyourworkspace.

    3. Checkoutthe release-v1.7.0 branch,orthebranchofalaterversion.

    4. Copythe google-services.json filefromearlierintothe app directoryoftheHeartbeatMonitorproject.

    5. OpenaprojectinAndroidStudiousingtherepoyoucloned.

    6. Update pivotal.properties filelocatedin app/src/main/res/raw :pivotal.push.platformUuid :ThisvaluemustmatchtheplatformUUIDoftheAndroid FCM Heartbeat PlatforminthePushdashboard.pivotal.push.platformSecret :ThisvaluemustmatchtheplatformSECREToftheAndroid Heartbeat FCM PlatforminthePushdashboard.pivotal.push.serviceUrl :EntertheserveraddresstoyourpushbackendAPIintheformof https://push-api.YOUR-SYSTEM-DOMAIN .

    7. CompileanddeploytheapplicationtoyourAndroiddevice.

    8. OpentheapponyourdeviceandselectAllowwhentheappasksifitcansendyounotifications.Thescreenupdateswithanewheartbeatcounteveryminuteasitreceivespushesfromyourenvironment.

    Note:Toverifythatyourdeviceregistered,seetheDevicestabinthePushdashboard.ThedeviceTypefielddisplaysaFirebaselogo.

    Note:IfyousendatestpushtoyourdevicefromthePushdashboard,ensuretheappisnotopenonyourdevice.Youcannotseethetestpushwhiletheappisopen.

    ©CopyrightPivotalSoftwareInc,2013-2018 25of117 1.7

    https://github.com/cfmobile/push-android-heartbeatmonitor

  • ©CopyrightPivotalSoftwareInc,2013-2018 26of117 1.7

  • Using the Dashboard V1.7.0

    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 27of117 1.7

    http://docs.pivotal.io/push/1-7/dashboard-user-guide-other.html

  • 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 28of117 1.7

  • OntheConfigurationpage,clickonthe AddNewPlatform

    button.Fillintheformandclick Save tocreatetheplatform.

    EditingaplatformOntheConfigurationpage,clickonthepenciliconlinknexttotheplatformyouwanttoedit.Editthefieldsandclick Save toupdatetheplatform.TheTypefieldcannotbechangedonceset.

    ©CopyrightPivotalSoftwareInc,2013-2018 29of117 1.7

  • DeletingaplatformOntheConfigurationpage,clickonthetrashiconlinknexttotheplatformyouwanttodelete.NOTE:Youcannotdeleteaplatformthathasdevices.Inordertoremovedevicesyoumustunregisterfromthedevice.

    DevicesAdeviceisgivenauniqueidentifierwhichrepresentsauseroptingintoreceivepushnotifications.Thisidentifierisnotnecessarilyuniquetoadevicesinceitmightchangeiftheuserreinstallsthemobileapplication,orunsubscribesandresubscribes.

    ©CopyrightPivotalSoftwareInc,2013-2018 30of117 1.7

  • SendatestpushnotificationtoadeviceClickon'Devices’inthesidebarmenu.Clickonthe Test

    Pushbuttonnexttothedevice.Filloutthepushform.See“Sendingapushmessage”fordetails

    ontheformfields.

    SendingaPushMessage

    ©CopyrightPivotalSoftwareInc,2013-2018 31of117 1.7

  • 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 32of117 1.7

  • iOS OnlySendingapushtoadeviceusinganinvalid .p12 certificatesetupinthedevice’scorrespondingplatformresultsinthedevicegettingremovedfromtheplatform.

    TagsAtagallowspushnotificationstobesenttoalldevicesthathaveexplicitlysubscribedtoitasopposedtoallusersthathavetheapplicationinstalled.Thisallowsanapplicationtosendtargetedpushnotificationstoasubsetofdevices.Devicescansubscribetotagsviatheregistrationsapi.AvailabletagsarelistedinthetargettingsectionoftheCreateNotificationform.

    LocationsLocationsallowyoutosendpushnotificationstoasubsetofuserswhoarewithin(orenter)theradiusofaspecifiedarea.

    AddingaLocationGroupClick Locations ontheleftsidebarandthenclickthe AddLocation button.

    ©CopyrightPivotalSoftwareInc,2013-2018 33of117 1.7

  • 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 34of117 1.7

  • GeofencePushNotificationsFillinthedetailsofthePushNotification,suchasMessage,Platform,andSchedule.Selectfromthe TargetLocation drop-downeitheraLocationoraLocationGroup.TriggerTypefieldwillappearupontheadditionofLocation/LocationGroup.SelecteitherEnterorExit,dependingonhowyouwanttheGeofencetoactivate.Onceallthedetailsareset,clickthe SendPush

    Notificationbutton.

    ©CopyrightPivotalSoftwareInc,2013-2018 35of117 1.7

  • LogsTheLogspagedisplaysanyloggedeventsthatoccurwhiletheLogspageisopen.Clickingthe“DownloadLogs”buttonwillcopythelogsdisplayedintoatextfileontoyourlocalmachine.

    ©CopyrightPivotalSoftwareInc,2013-2018 36of117 1.7

  • 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 37of117 1.7

    http://docs.pivotal.io/pivotalcf/adminguide/app-sec-groups.html

  • [{"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 38of117 1.7

  • ©CopyrightPivotalSoftwareInc,2013-2018 39of117 1.7

  • 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 40of117 1.7

    https://support.apple.com/en-ca/HT203609https://gcm-http.googleapis.com/gcm/send

  • Development GuideFirstPushWalkthrough

    FirstGeofenceWalkthrough

    iOS

    SampleApp

    Android

    SampleApp

    WindowsPhone8.1

    SampleApp

    ©CopyrightPivotalSoftwareInc,2013-2018 41of117 1.7

    https://github.com/cfmobile/push-ios-sampleshttps://github.com/cfmobile/push-android-sampleshttps://github.com/cfmobile/push-wp81-samples

  • First Push WalkthroughStep1IntheCloudFoundryAppManager,clickonthe“Marketplace”link.Select“PushNotificationService”fromthelistofavailableservices.

    Step2Selectthe“Default”serviceplan.GivetheserviceinstanceanameandmakesuretoselectthecorrectSpacefortheservicetobecreatedinbeforeclickingthe“Add”button.

    Step3Youcannowclickonthe“Manage”linkforthePushNotificationsServiceinstanceyou’vecreated.ThiswillopenthePushDashboard.

    ©CopyrightPivotalSoftwareInc,2013-2018 42of117 1.7

  • 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 43of117 1.7

    https://console.developers.google.com

  • 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 44of117 1.7

    https://developer.apple.com

  • Step9Fillinamessageandpresssendtosendatestmessage.

    Step10Iftheserveracceptsthispushfordelivery,areceiptwillbeshownonscreen.Thisdoesnotguaranteedeliverytothedevice(devicecouldbeoff,notificationscouldbedisabled,etc).

    ©CopyrightPivotalSoftwareInc,2013-2018 45of117 1.7

  • 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 46of117 1.7

  • 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 47of117 1.7

  • ©CopyrightPivotalSoftwareInc,2013-2018 48of117 1.7

  • 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 49of117 1.7

    https://github.com/cfmobile/push-ios-samples/releases/tag/1.5.0http://docs.pivotal.io/push/1-7/ios/1.4.0/http://docs.pivotal.io/push/1-7/ios/1.3.3/http://docs.pivotal.io/push/1-7/ios/1.3.2/http://docs.pivotal.io/push/1-7/ios/1.3.1/http://docs.pivotal.io/push/1-7/ios/1.3.0/http://docs.pivotal.io/push/1-7/ios/1.0.4/https://network.pivotal.io/products/push-notification-service

  • 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 50of117 1.7

    https://www.openssl.org/docs/manmaster/man1/rsa.html

  • -(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

    Inyourapplicationdelegate’s application:didRegisterforRemoteNotifications: methodputthefollowingcode:

    ©CopyrightPivotalSoftwareInc,2013-2018 51of117 1.7

    https://developer.apple.com/library/ios/documentation/uikit/reference/UIApplication_Class/Reference/Reference.html#//apple_ref/doc/c_ref/UIRemoteNotificationType

  • //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 52of117 1.7

    http://docs.pivotal.io/push/1-7/custom-user-id-format.html

  • -(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 53of117 1.7

  • //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 54of117 1.7

  • 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 55of117 1.7

  • Step2-Setrequireddevicecapabilities

    Addlocation-servicesandgpstoyourapplicationInfo.plistfileunder“Requireddevicecapabilities”.

    Step3-Setyourlocationusagedescription

    IfthisisthefirsttimethatyourappisusinganylocationservicesthenyouwillneedtosetthetextthatisdisplayedoniOS8.0+whentheappfirstrequeststhepermissiontoreadyourcurrentdevicelocation.Youcansetthistextbysettingthe NSLocationAlwaysUsageDescription keyinyourapp’sInfo.plistfile(containedinSupportingFilesfolderbydefault).e.g.:“YourAppNamewouldliketoreadyourcurrentlocationandmonitorgeofences(ifenabled).”

    ©CopyrightPivotalSoftwareInc,2013-2018 56of117 1.7

  • 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 57of117 1.7

  • 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

    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 58of117 1.7

  • 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.

    Inorderforthismethodtotakeeffectyouwillneedtocallitbothbefore [PCFPushregisterForPCFPushNotificationsWithDeviceToken:...] andalsobefore[PCFPushdidReceiveRemoteNotification:...]

    .

    example:

    ©CopyrightPivotalSoftwareInc,2013-2018 59of117 1.7

  • @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.

    Inorderforthismethodtotakeeffectyouwillneedtocallitbefore 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 60of117 1.7

    https://developer.apple.com/library/mac/documentation/Foundation/Reference/NSURLConnectionDelegate_Protocol/index.html#//apple_ref/occ/intfm/NSURLConnectionDelegate/connection:willSendRequestForAuthenticationChallenge:https://developer.apple.com/library/prerelease/ios/technotes/App-Transport-Security-Technote/index.html

  • NSAppTransportSecurity

    NSExceptionDomainsyourserver.comNSIncludesSubdomainsNSExceptionAllowsInsecureHTTPLoads

    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 61of117 1.7

    https://developer.apple.com/library/ios/documentation/IDEs/Conceptual/AppDistributionGuide/ConfiguringPushNotifications/ConfiguringPushNotifications.html#//apple_ref/doc/uid/TP40012582-CH32-SW1

  • 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 62of117 1.7

    http://docs.pivotal.io/push/1-7/troubleshooting.html#iosSDK

  • 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 63of117 1.7

    https://github.com/cfmobile/push-android-sampleshttp://docs.pivotal.io/push/1-7/android/1.4.0/http://docs.pivotal.io/push/1-7/android/1.3.3/http://docs.pivotal.io/push/1-7/android/1.3.2/http://docs.pivotal.io/push/1-7/android/1.3.1/http://docs.pivotal.io/push/1-7/android/1.3.0/http://docs.pivotal.io/push/1-7/android/1.0.4/https://network.pivotal.io/products/push-notification-service

  • 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:

    Youneedtoaddthefollowing receiver tothe application elementofyourapp’s AndroidManifest.xml file.Ensurethatyousetthecategory nametoyourapp’spackage name:

    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 .IfyouusetheSDKv1.7,thenusethetype Android-FCM .

    Forinstructionsonhowtoconvertyour PEM certificatefilesto DER ,seetheOpenSSLdocumentation .

    Notethatthe pivotal.push.trustAllSslCertificates propertywasremovedinPCFPushClientSDKv1.3.3.

    ©CopyrightPivotalSoftwareInc,2013-2018 64of117 1.7

    https://network.pivotal.io/products/p-push-notificationshttp://openssl.org/docs/apps/rsa.html

  • 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 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 65of117 1.7

  • finalSettags=newHashSet();tags.add("breaking_news");tags.add("local_news");Push.getInstance(this).startRegistration(null,null,tags,false,null);