A sample project to show the easiness of integrating Bluemix Push service, Mobile Analytics and AppID service across different platform (mobile and web).
- Chrome(56)/Firefox(51)
- Cloud Foundry or Bluemix CLI
- iOS 8.0+
- Xcode 8.+
- Swift 3.+
- Cocoapods
-
Create a Push Notifications Service.
-
Create an AppID Service
-
Create a Mobile Anlytics Service.
Note: For service credentials, click on Credentials tab on the left pane.
Clone the ICLab-OmniChannelAppDev repo
git clone https://github.com/ibm-bluemix-omnichannel-iclabs/ICLab-OmniChannelAppDev.git
-
Go to https://console.firebase.google.com/ and Add a Project. Under settings Icon next to
Overview
, Click onCLOUD MESSAGING
section to get Legacy Server key and Sender ID.
Note: Keep this tab open on your browser for future reference.
Go to the ICLab-OmniChannelAppDev/Web
in your cloned repo and follow the below steps,
-
Go to the
Web/manifest.yml
file. Change thehost
andname
to a unique name of your choice and add theAPP ID
service name you created above. -
Open
views/protected.ejs
file,
-
Add the
manifest.json
file<link rel="manifest" href="manifest.json">
-
under
<script>
tag, add the Configurations. Add the appropriate service credentials by navigating to Bluemix.net.For
Push Notification
,var initParams = { "appGUID":"<Push Service APPGUID>", "appRegion":"<Push Service Region>", "clientSecret":"<Push service clientSecret>" }
For
Analytics
,var appName = "<Analytics Service Name>"; var apiKey = "<Analytics service API Key>"; var hasUserContext=true; var tenantId = "<Analytics Service tenantID>";
Note: Get the Analytics Service tenantID
from the URL path of the Analytics Service.
-
If you don't see
bmsanalytics.js, BMSPushSDK.js, BMSPushServiceWorker.js
andmanifest.json
file under /Web/views folder. Download these Push Service website SDKs from Push Web SDK, Ananlytics SDK and paste them inside /web/views folder -
Open the
views/manifest.json
file and add values forname
andgcm_sender_id (Sender ID)
. -
Push to Bluemix using Bluemix CLI,
- Go to the folder Web in your terminal.
- Run the CLI command - cf api api.stage1.ng.bluemix.net ,
- Login to Bluemix from CLI using cf login. Select your Organization and Space.
- Do the cf push. This will host your app in Bluemix.
- After App is started open - https://yourwebsitename.mybluemix.net.
-
Open the
Bluemix Push service
and add thewebsites address
andGoogle server Keys (Legacy Server key)
. -
Open the Analytics RestSPI and add your website URL in allowedUrls. Use the
v3/serviceConf
POST method underService Configuration
.
Click on the Login
option and login with AppID
. After Successfully loggin you'll be able to register for Push notificatons
. Later you can send push notifications from Push Service Dashboard.
Send Push notifications web application.
-
Got to the Push Service Dashboard and send message
-
You can see the notification in
Browser (Chrome and Firefox)
Check the Analytics details by visiting to the Analytics dashboard.
Go to the ICLab-OmniChannelAppDev/iOS in your cloned repo and open the Podfile
- Add the following pod dependencies
target 'BMDService' do
use_frameworks!
pod 'BluemixAppID', :git => 'https://github.com/ibm-bluemix-mobile-services/appid-clientsdk-swift.git', :branch => ‘development’
pod 'BMSPush'
pod 'BMSAnalytics'
end
-
Do the
pod install
in your Terminal app inside the iOS. -
Open the
BMDService.xcworkspace
app in Xcode -
Add your
Bundle identifier
and configure forpush service
. Follow [this](https://console. .ng.bluemix.net/docs/services/mobilepush/t__main_push_config_provider.html#create-push-credentials-apns) -
Enable
Push Notification
,Background mode -> Remote notifications
andKeychain Sharing
-
Go to the
Targets -> Info
and addURL Types
. Set values for bothIdentifier
andURL Schemes
as$(PRODUCT_BUNDLE_IDENTIFIER)
-
Open
AppDelegate.swift
file and add values for the following,
let appIdTenantId = "ClientId of your APPID Service"
let appRegion = "your service region"
let pushAPPGUID = "App Guid of your Push Notification Service"
let pushClientSecret = "Client Secret of your Push Notification Service"
let ananlyticsAppName = "BMDService"
let ananlyticsApiKey = "API Key of your Mobile Analytics Service.”
-
Initialize the
BMSCore
,APPID
andAnalytics
SDKs insidedidFinishLaunchingWithOptions
method -
Add the code to handle
APPID
call back function
func application(_ application: UIApplication, open url: URL, options :[UIApplicationOpenURLOptionsKey : Any]) -> Bool {
return AppID.sharedInstance.application(application, open: url, options: options)
}
- Create a method named
registerForPush
and initializeBMSPush
func registerForPush() {
BMSPushClient.sharedInstance.initializeWithAppGUID(appGUID: pushAPPGUID, clientSecret:pushClientSecret)
}
- Add code to register to Push Notification Service inside
didRegisterForRemoteNotificationsWithDeviceToken
method
BMSPushClient.sharedInstance.registerWithDeviceToken(deviceToken: deviceToken) { (response, status, error) in
if error.isEmpty {
print( "Response during device registration : \(response)")
print( "status code during device registration : \(status)")
self.showAlert(title: "Success!!!", message: "Response during device registration : \(response)" )
}else{
print( "Error during device registration \(error) ")
self.showAlert(title: "Error!!!", message: "Error during device registration \(error)" )
}
}
- Add code for sending
Analytics
data.
let logger = Logger.logger(name: "My Logger")
logger.debug(message: "Successfully registered for push")
logger.info(message: "Successfully registered for push")
Analytics.userIdentity = self.userID
Analytics.log(metadata: ["event": "Successfully registered for push"])
Analytics.log(metadata: ["Logged in" : self.userID])
Logger.send(completionHandler: { (response: Response?, error: Error?) in
if let response = response {
print("Status code: \(response.statusCode)")
print("Response: \(response.responseText)")
}
if let error = error {
logger.error(message: "Failed to send logs. Error: \(error)")
}
})
Analytics.send(completionHandler: { (response: Response?, error: Error?) in
if let response = response {
print("Status code: \(response.statusCode)")
print("Response: \(response.responseText)")
}
if let error = error {
logger.error(message: "Failed to send analytics. Error: \(error)")
}
})
-
Add code to handle the Push Notification, inside
didReceiveRemoteNotification
-
Inside
LoginViewController.swift
, add code for usingAPPID Service
login. Add the code insidelog_inAppID
method.
@IBAction func log_inAppID(_ sender: AnyObject) {
loaderActivity.isHidden = false;
//Invoking AppID login
class delegate : AuthorizationDelegate {
var view:UIViewController
init(view:UIViewController) {
self.view = view
}
public func onAuthorizationSuccess(accessToken: AccessToken, identityToken: IdentityToken, response:Response?) {
let mainView = UIApplication.shared.keyWindow?.rootViewController
let afterLoginView = UIStoryboard(name: "Main", bundle: nil).instantiateViewController(withIdentifier: "ProfileViewController") as? ProfileViewController
afterLoginView?.accessToken = accessToken
afterLoginView?.idToken = identityToken
DispatchQueue.main.async {
mainView?.present(afterLoginView!, animated: true, completion: nil)
}
}
public func onAuthorizationCanceled() {
print("cancel")
}
public func onAuthorizationFailure(error: AuthorizationError) {
print(error)
}
}
AppID.sharedInstance.loginWidget?.launch(delegate: delegate(view: self))
}
- Run your iOS application
-
You can Register for push Notification using the Enable Push switch.
-
Use the Crash Your App switch to crash the app. This will store the crash report in Analytics and next time you open the app it will send crash report to the Mobile Analytics service.
Send Push notifications iOS application.
-
Got to the Push Service Dashboard and send message
-
You can see the notification in iOS device
Copyright 2017-2018 IBM Corporation
Licensed under the Apache License, Version 2.0 (the "License").
Unless required by applicable law or agreed to in writing, software distributed under the license is distributed on an "as is" basis, without warranties or conditions of any kind, either express or implied. See the license for the specific language governing permissions and limitations under the license.