-
Notifications
You must be signed in to change notification settings - Fork 194
Expand file tree
/
Copy pathcontrollers.js
More file actions
179 lines (160 loc) · 8.05 KB
/
controllers.js
File metadata and controls
179 lines (160 loc) · 8.05 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
/**
* Author: hollyschinsky
* twitter: @devgirfl
* blog: devgirl.org
* more tutorials: hollyschinsky.github.io
*/
app.controller('AppCtrl', function($scope, $cordovaPush, $cordovaDialogs, $cordovaMedia, $cordovaToast, ionPlatform, $http) {
$scope.notifications = [];
// call to register automatically upon device ready
ionPlatform.ready.then(function (device) {
if (window.localStorage['regid'] !== "true") {
$scope.register();
console.log("regid is not true so registering the device for push notification");
} else {
console.log("regid is true so need for registering");
}
});
// Register
$scope.register = function () {
var config = null;
if (ionic.Platform.isAndroid()) {
config = {
"senderID": "YOUR_GCM_PROJECT_ID" // REPLACE THIS WITH YOURS FROM GCM CONSOLE - also in the project URL like: https://console.developers.google.com/project/434205989073
};
}
else if (ionic.Platform.isIOS()) {
config = {
"badge": "true",
"sound": "true",
"alert": "true"
}
}
$cordovaPush.register(config).then(function (result) {
console.log("Register success " + result);
$cordovaToast.showShortCenter('Registered for push notifications');
$scope.registerDisabled=true;
// ** NOTE: Android regid result comes back in the pushNotificationReceived, only iOS returned here
if (ionic.Platform.isIOS()) {
$scope.regId = result;
storeDeviceToken("ios");
}
}, function (err) {
console.log("Register error " + err)
});
}
// Notification Received
$scope.$on('$cordovaPush:notificationReceived', function (event, notification) {
console.log(JSON.stringify([notification]));
if (ionic.Platform.isAndroid()) {
handleAndroid(notification);
}
else if (ionic.Platform.isIOS()) {
handleIOS(notification);
$scope.$apply(function () {
$scope.notifications.push(JSON.stringify(notification.alert));
})
}
});
// Android Notification Received Handler
function handleAndroid(notification) {
// ** NOTE: ** You could add code for when app is in foreground or not, or coming from coldstart here too
// via the console fields as shown.
console.log("In foreground " + notification.foreground + " Coldstart " + notification.coldstart);
if (notification.event == "registered") {
$scope.regId = notification.regid;
storeDeviceToken("android");
}
else if (notification.event == "message") {
$cordovaDialogs.alert(notification.message, "Push Notification Received");
$scope.$apply(function () {
$scope.notifications.push(JSON.stringify(notification.message));
})
}
else if (notification.event == "error")
$cordovaDialogs.alert(notification.msg, "Push notification error event");
else $cordovaDialogs.alert(notification.event, "Push notification handler - Unprocessed Event");
}
// IOS Notification Received Handler
function handleIOS(notification) {
// The app was already open but we'll still show the alert and sound the tone received this way. If you didn't check
// for foreground here it would make a sound twice, once when received in background and upon opening it from clicking
// the notification when this code runs (weird).
if (notification.foreground == "1") {
// Play custom audio if a sound specified.
if (notification.sound) {
var mediaSrc = $cordovaMedia.newMedia(notification.sound);
mediaSrc.promise.then($cordovaMedia.play(mediaSrc.media));
}
if (notification.body && notification.messageFrom) {
$cordovaDialogs.alert(notification.body, notification.messageFrom);
}
else $cordovaDialogs.alert(notification.alert, "Push Notification Received");
if (notification.badge) {
$cordovaPush.setBadgeNumber(notification.badge).then(function (result) {
console.log("Set badge success " + result)
}, function (err) {
console.log("Set badge error " + err)
});
}
}
// Otherwise it was received in the background and reopened from the push notification. Badge is automatically cleared
// in this case. You probably wouldn't be displaying anything at this point, this is here to show that you can process
// the data in this situation.
else {
if (notification.body && notification.messageFrom) {
$cordovaDialogs.alert(notification.body, "(RECEIVED WHEN APP IN BACKGROUND) " + notification.messageFrom);
}
else $cordovaDialogs.alert(notification.alert, "(RECEIVED WHEN APP IN BACKGROUND) Push Notification Received");
}
}
// Stores the device token in a db using node-pushserver (running locally in this case)
//
// type: Platform type (ios, android etc)
function storeDeviceToken(type) {
// Create a random userid to store with it
var user = { user: 'user' + Math.floor((Math.random() * 10000000) + 1), type: type, token: $scope.regId };
console.log("Post token for registered device with data " + JSON.stringify(user));
$http.post('http://192.168.1.16:8000/subscribe', JSON.stringify(user))
.success(function (data, status) {
console.log("Token stored, device is successfully subscribed to receive push notifications.");
window.localStorage['regid'] = true;
})
.error(function (data, status) {
console.log("Error storing device token." + data + " " + status)
$cordovaToast.showLongBottom('The app is unable to register for push notification, try again later by repopening the app');
}
);
}
// Removes the device token from the db via node-pushserver API unsubscribe (running locally in this case).
// If you registered the same device with different userids, *ALL* will be removed. (It's recommended to register each
// time the app opens which this currently does. However in many cases you will always receive the same device token as
// previously so multiple userids will be created with the same token unless you add code to check).
function removeDeviceToken() {
var tkn = {"token": $scope.regId};
$http.post('http://192.168.1.16:8000/unsubscribe', JSON.stringify(tkn))
.success(function (data, status) {
console.log("Token removed, device is successfully unsubscribed and will not receive push notifications.");
})
.error(function (data, status) {
console.log("Error removing device token." + data + " " + status)
}
);
}
// Unregister - Unregister your device token from APNS or GCM
// Not recommended: See http://developer.android.com/google/gcm/adv.html#unreg-why
// and https://developer.apple.com/library/ios/documentation/UIKit/Reference/UIApplication_Class/index.html#//apple_ref/occ/instm/UIApplication/unregisterForRemoteNotifications
//
// ** Instead, just remove the device token from your db and stop sending notifications **
$scope.unregister = function () {
console.log("Unregister called");
removeDeviceToken();
$scope.registerDisabled=false;
//need to define options here, not sure what that needs to be but this is not recommended anyway
// $cordovaPush.unregister(options).then(function(result) {
// console.log("Unregister success " + result);//
// }, function(err) {
// console.log("Unregister error " + err)
// });
}
})