For iOS client apps, you can implement GCM messaging in two complementary ways:
Receive basic push messages up to 2KB over GCM's APNs interface. To implement this:
- You need a valid APNs certificate. If you don't already have one, see Provision APNs SSL Certificates.
- Set up CocoaPods dependencies.
- Configure your project.
- Obtain a GCM registration token.
Send messages upstream and/or receive downstream payloads up to 4KB. To implement this:
- Perform all setup tasks required for basic push messaging.
- Set up and connect to the GCM service.
To write your client code in objective-C or Swift, we recommend that you use the Google Cloud Messaging for iOS API. The GCM iOS quickstart example provides sample code for both languages, covering all the steps described in this page.
Create an API project
New Cloud Messaging projects must create a Firebase project in the Firebase console. In this process, you'll generate a configuration file and credentials for your project.
- Create a Firebase project in the Firebase console, if you don't already have one. If you already have an existing Google project associated with your mobile app, click Import Google Project. Otherwise, click Create New Project.
- Click Add Firebase to your iOS app and follow the setup steps. If you're importing an existing Google project, this may happen automatically and you can just download the config file.
- When prompted, enter your app's bundle ID. It's important to enter the bundle ID your app is using; this can only be set when you add an app to your Firebase project.
- At the end, you'll download a
GoogleService-Info.plistfile. You can download this file again at any time. - If you haven't done so already, copy this into your Xcode project root.
Add the configuration file to your project
Drag the GoogleService-Info.plist file you just
downloaded into the root of your Xcode project and add it to all targets.
Obtain a Registration Token
Before it can receive messages, an iOS application needs to register with both Apple Push Notification service (APNs) and the GCM connection server. When a client app registers with GCM, it receives a registration token, which it must then send to the app server (the APNs device token is not sent to the server). The client app must store a boolean value indicating whether the registration token has been sent to the server.
To register with APNs and obtain a GCM registration token:-
Include the GCM header:
#import <Google/CloudMessaging.h>
-
Register for remote notifications and obtain an APNs token. For detailed instructions, see Registering, Scheduling, and Handling User Notifications.
- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions { // ... UIUserNotificationType allNotificationTypes = (UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge); UIUserNotificationSettings *settings = [UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil]; [[UIApplication sharedApplication] registerUserNotificationSettings:settings]; [[UIApplication sharedApplication] registerForRemoteNotifications]; }- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken { -
Configure and initialize Instance ID, and call
tokenWithAuthorizedEntity:scope:options:handler:with the following arguments:-
The app server sender ID
-
The
kGGLInstanceIDScopeGCMscope, as defined inGGLInstanceID.h -
The APNs token, set as part of the options dictionary, with the key
kGGLInstanceIDRegisterAPNSOptionand the value set to the binary APNS token -
kGGLInstanceIDAPNSServerTypeSandboxOptionwith a value ofYESfor sandbox orNOfor production environment. This is part of the options dictionary.
// Create a config and set a delegate that implements the GGLInstaceIDDelegate protocol. GGLInstanceIDConfig *instanceIDConfig = [GGLInstanceIDConfig defaultConfig]; instanceIDConfig.delegate = self; // Start the GGLInstanceID shared instance with the that config and request a registration // token to enable reception of notifications [[GGLInstanceID sharedInstance] startWithConfig:instanceIDConfig]; _registrationOptions = @{kGGLInstanceIDRegisterAPNSOption:deviceToken, kGGLInstanceIDAPNSServerTypeSandboxOption:@YES}; [[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID scope:kGGLInstanceIDScopeGCM options:_registrationOptions handler:_registrationHandler]; -
- Once you have retrieved the token, send it to your app server.
If registration was successful, InstanceID invokes the
registrationToken handler with a valid registration token and a nil error object.
If registration instead fails, the registration token is nil and a valid error object is returned.
For details on the error codes, see GGLInstanceID.h. When registration
fails, client apps should implement
exponential backoff to try again.
Handle refreshed tokens
To handle cases where the registration token has been refreshed, the GGLInstanceIDDelegate protocol
declares an onTokenRefresh method that is called when the system determines that tokens need to be refreshed.
- (void)onTokenRefresh {
// A rotation of the registration tokens is happening, so the app needs to request a new token.
NSLog(@"The GCM registration token needs to be changed.");
[[GGLInstanceID sharedInstance] tokenWithAuthorizedEntity:_gcmSenderID
scope:kGGLInstanceIDScopeGCM
options:_registrationOptions
handler:_registrationHandler];
}
To handle token refreshes the client app should:
-
Declare a class that adopts the
GGLInstanceIDDelegateprotocol; -
Set that class as delegate on the
GGLInstanceIDConfigusing thedelegateproperty.
An example GCM registration token looks like this:
bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1pLTQ/8t-5QNiXbYwZYEWiSFD-frQKlsV8lgI
For full details on the Instance ID API, see its API reference.
Import existing APNs tokens
If you have an existing user base that you want to onboard to a GCM-enabled client app, use the batchImport API provided by Instance ID. With this API, you can bulk import existing iOS APNs tokens into GCM, mapping them to new, valid registration tokens.
Receive messages through the GCM APNs interface
Once your client app has a registration token, it can receive messages through
the GCM APNs interface. Your application server can send messages with a
notification
payload through GCM's APNs interface. If you need to set the content-available
key of the the APNs aps dictionary, you can set content_available to true.
The following examples show how you can send a notification through the GCM APNs interface.
HTTP POST request
https://gcm-http.googleapis.com/gcm/send
Content-Type:application/json
Authorization:key=AIzaSyZ-1u...0GBYzPu7Udno5aA
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark"
}
}
XMPP message
<message id="">
<gcm xmlns="google:mobile:data">
{
"to" : "bk3RNwTe3H0:CI2k_HHwgIpoDKCIZvvDMExUdFQ3P1...",
"notification" : {
"body" : "great match!",
"title" : "Portugal vs. Denmark"
}
}
</gcm>
</message>
Set up and connect to GCM
For your client app to use GCM's full messaging capabilites beyond simple APNs
messaging, you'll need to set up the GCM service and connect to your GCM connection
server. Use +(instancetype)sharedInstance to access the GCM Service, and
because GCM is not thread-safe, call all GCMService
methods on the main thread.
Configure and start GCM
-
Configure GCM properties.
-
GCMConfig.hdefines the set of GCM properties. Use[GCMConfig defaultConfig]to get the default config object and predefined values. -
Set the config object to values based on the client app’s needs.
-
-
Start GCMService.
- Call
[GCMService startWithConfig:<config>]with the config from the preceding step. This instantiates GCM services for the client app.
- Call
GCMConfig is loaded once
during GCM initialization. Changes to the configuration properties after initialization
has no effect on the properties.
To stop GCMService, call [GCMService teardown]
with the instances associated with it. When you stop the service, all of the objects
that GCM owns are changed to nil, and all services or requests that GCM has created are stopped.
Call this method once in the lifecycle of the client app, only when there is
no need to use GCM anymore. When the client app is in the background and needs to
release relevant resources, use disconnect as described
in Stop receiving messages.
Connect to GCM
To send messages via the GCM connection server, call [connectWithHandler:handler]
on the application's main thread to connect with the server whenever the client
app is in the foreground:
- (void)applicationDidBecomeActive:(UIApplication *)application {
// Connect to the GCM server to receive non-APNS notifications
[[GCMService sharedInstance] connectWithHandler:^(NSError *error) {
if (error) {
NSLog(@"Could not connect to GCM: %@", error.localizedDescription);
} else {
_connectedToGCM = true;
NSLog(@"Connected to GCM");
// ...
}
}];
}
The handler is invoked when the GCM connection server responds with a connection status.
The NSError object is nil if the connection is successful. And a custom duplex
connection is established with the GCM connection server.
NSError contains the failure reason if the client app disconnects and the
connection fails. See Common error codes for more information.
When the connection fails initially, GCM tries again with exponential backoff. At the end of each backoff period, the handler is invoked again. This process continues until the connection is successfully established or the client app disconnects.
Disconnect GCM
Call ([GCM disconnect]) when your app goes into the background. This releases
resources until your app returns to the foreground, at which point it can
reconnect.
Next steps
Once the client app is connected, you are ready to start receiving downstream messages and sending upstream messages. For more information about your options with GCM, see also guides for topic messaging and device group messaging as well as the reference information for both client and server APIs.
Stop requests
The default timeout for all requests is 60 seconds. To cancel a request before
the full timeout period has elapsed, call the
stopAllRequests method.
[[GGLInstanceID sharedInstance] stopAllRequests]
Common error codes
The error codes most commonly returned to the client are shown in the
following table. For complete lists of the error codes related to GCM registration
and connection, see GGLInstanceID.h and GCMService.h.
| Error Code | Error | Description |
| 0 | Invalid Request | Some parameters of the request were invalid. |
| 1 | Auth Error | The GCM connection server couldn’t authenticate the client. |
| 2 | No Access | GCM service cannot be accessed. |
| 3 | Timeout | The request to GCM timed out. |
| 4 | Network | No network available to reach GCM. |
| 5 | Operation In Progress | Another similar operation is in progress. This one was canceled. |
| 7 | Unknown | Unknown error. |