-
GCM(Google Cloud Messaging)App/Objective-C 2017. 2. 24. 14:32
GCM이란? 말그대로 구글에서 제공하는 알림 메시지 기능이다.
서버측에서 데이터를 조작하여 앱에 알림바 형태로 제공할 수 있는 기능이며,
이전에는 IOS에서는 APNS Android에서는 GCM을 이용하곤 했는데,
몇년전에 통합되어 GCM으로 두 서비스 제공이 가능해졌다.
//AppDelegate.h
12345678910111213#import <Google/CloudMessaging.h>#import <UIKit/UIKit.h>@interface AppDelegate : UIResponder <UIApplicationDelegate, GGLInstanceIDDelegate, GCMReceiverDelegate>@property(nonatomic, strong) UIWindow *window;@property(nonatomic, readonly, strong) NSString *registrationKey;@property(nonatomic, readonly, strong) NSString *messageKey;@property(nonatomic, readonly, strong) NSString *gcmSenderID;@property(nonatomic, readonly, strong) NSDictionary *registrationOptions;@endcs //AppDelegate.m
123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231//// Copyright (c) 2015 Google Inc.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// 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.//#import "AppDelegate.h"@interface AppDelegate ()@property(nonatomic, strong) void (^registrationHandler)(NSString *registrationToken, NSError *error);@property(nonatomic, assign) BOOL connectedToGCM;@property(nonatomic, strong) NSString* registrationToken;@property(nonatomic, assign) BOOL subscribedToTopic;@endNSString *const SubscriptionTopic = @"/topics/global";@implementation AppDelegate// [START register_for_remote_notifications]- (BOOL)application:(UIApplication *)applicationdidFinishLaunchingWithOptions:(NSDictionary *)launchOptions {// [START_EXCLUDE]_registrationKey = @"onRegistrationCompleted";_messageKey = @"onMessageReceived";// Configure the Google context: parses the GoogleService-Info.plist, and initializes// the services that have entries in the fileNSError* configureError;[[GGLContext sharedInstance] configureWithError:&configureError];NSAssert(!configureError, @"Error configuring Google services: %@", configureError);_gcmSenderID = [[[GGLContext sharedInstance] configuration] gcmSenderID];// Register for remote notificationsif (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {// iOS 7.1 or earlierUIRemoteNotificationType allNotificationTypes =(UIRemoteNotificationTypeSound | UIRemoteNotificationTypeAlert | UIRemoteNotificationTypeBadge);[application registerForRemoteNotificationTypes:allNotificationTypes];} else {// iOS 8 or later// [END_EXCLUDE]UIUserNotificationType allNotificationTypes =(UIUserNotificationTypeSound | UIUserNotificationTypeAlert | UIUserNotificationTypeBadge);UIUserNotificationSettings *settings =[UIUserNotificationSettings settingsForTypes:allNotificationTypes categories:nil];[[UIApplication sharedApplication] registerUserNotificationSettings:settings];[[UIApplication sharedApplication] registerForRemoteNotifications];}// [END register_for_remote_notifications]// [START start_gcm_service]GCMConfig *gcmConfig = [GCMConfig defaultConfig];gcmConfig.receiverDelegate = self;[[GCMService sharedInstance] startWithConfig:gcmConfig];// [END start_gcm_service]__weak typeof(self) weakSelf = self;// Handler for registration token request_registrationHandler = ^(NSString *registrationToken, NSError *error){if (registrationToken != nil) {weakSelf.registrationToken = registrationToken;NSLog(@"Registration Token: %@", registrationToken);[weakSelf subscribeToTopic];NSDictionary *userInfo = @{@"registrationToken":registrationToken};[[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKeyobject:niluserInfo:userInfo];} else {NSLog(@"Registration to GCM failed with error: %@", error.localizedDescription);NSDictionary *userInfo = @{@"error":error.localizedDescription};[[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKeyobject:niluserInfo:userInfo];}};return YES;}- (void)subscribeToTopic {// If the app has a registration token and is connected to GCM, proceed to subscribe to the// topicif (_registrationToken && _connectedToGCM) {[[GCMPubSub sharedInstance] subscribeWithToken:_registrationTokentopic:SubscriptionTopicoptions:nilhandler:^(NSError *error) {if (error) {// Treat the "already subscribed" error more gentlyif (error.code == 3001) {NSLog(@"Already subscribed to %@",SubscriptionTopic);} else {NSLog(@"Subscription failed: %@",error.localizedDescription);}} else {self.subscribedToTopic = true;NSLog(@"Subscribed to %@", SubscriptionTopic);}}];}}// [START connect_gcm_service]- (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");// [START_EXCLUDE][self subscribeToTopic];// [END_EXCLUDE]}}];}// [END connect_gcm_service]// [START disconnect_gcm_service]- (void)applicationDidEnterBackground:(UIApplication *)application {[[GCMService sharedInstance] disconnect];// [START_EXCLUDE]_connectedToGCM = NO;// [END_EXCLUDE]}// [END disconnect_gcm_service]// [START receive_apns_token]- (void)application:(UIApplication *)applicationdidRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken {// [END receive_apns_token]// [START get_gcm_reg_token]// 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:_gcmSenderIDscope:kGGLInstanceIDScopeGCMoptions:_registrationOptionshandler:_registrationHandler];// [END get_gcm_reg_token]}// [START receive_apns_token_error]- (void)application:(UIApplication *)applicationdidFailToRegisterForRemoteNotificationsWithError:(NSError *)error {NSLog(@"Registration for remote notification failed with error: %@", error.localizedDescription);// [END receive_apns_token_error]NSDictionary *userInfo = @{@"error" :error.localizedDescription};[[NSNotificationCenter defaultCenter] postNotificationName:_registrationKeyobject:niluserInfo:userInfo];}// [START ack_message_reception]- (void)application:(UIApplication *)applicationdidReceiveRemoteNotification:(NSDictionary *)userInfo {NSLog(@"Notification received: %@", userInfo);// This works only if the app started the GCM service[[GCMService sharedInstance] appDidReceiveMessage:userInfo];// Handle the received message// [START_EXCLUDE][[NSNotificationCenter defaultCenter] postNotificationName:_messageKeyobject:niluserInfo:userInfo];// [END_EXCLUDE]}- (void)application:(UIApplication *)applicationdidReceiveRemoteNotification:(NSDictionary *)userInfofetchCompletionHandler:(void (^)(UIBackgroundFetchResult))handler {NSLog(@"Notification received: %@", userInfo);// This works only if the app started the GCM service[[GCMService sharedInstance] appDidReceiveMessage:userInfo];// Handle the received message// Invoke the completion handler passing the appropriate UIBackgroundFetchResult value// [START_EXCLUDE][[NSNotificationCenter defaultCenter] postNotificationName:_messageKeyobject:niluserInfo:userInfo];handler(UIBackgroundFetchResultNoData);// [END_EXCLUDE]}// [END ack_message_reception]// [START on_token_refresh]- (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:_gcmSenderIDscope:kGGLInstanceIDScopeGCMoptions:_registrationOptionshandler:_registrationHandler];}// [END on_token_refresh]// [START upstream_callbacks]- (void)willSendDataMessageWithID:(NSString *)messageID error:(NSError *)error {if (error) {// Failed to send the message.} else {// Will send message, you can save the messageID to track the message}}- (void)didSendDataMessageWithID:(NSString *)messageID {// Did successfully send message identified by messageID}// [END upstream_callbacks]- (void)didDeleteMessagesOnServer {// Some messages sent to this device were deleted on the GCM server before reception, likely// because the TTL expired. The client should notify the app server of this, so that the app// server can resend those messages.}@end
cs//ViewController.m
12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788//// Copyright (c) 2015 Google Inc.//// Licensed under the Apache License, Version 2.0 (the "License");// you may not use this file except in compliance with the License.// You may obtain a copy of the License at//// http://www.apache.org/licenses/LICENSE-2.0//// 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.//#import "AppDelegate.h"#import "ViewController.h"@implementation ViewController- (void)viewDidLoad {[super viewDidLoad];AppDelegate *appDelegate = (AppDelegate *)[[UIApplication sharedApplication] delegate];//NotificationCenter 등록[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(updateRegistrationStatus:)name:appDelegate.registrationKeyobject:nil];[[NSNotificationCenter defaultCenter] addObserver:selfselector:@selector(showReceivedMessage:)name:appDelegate.messageKeyobject:nil];_registrationProgressing.hidesWhenStopped = YES;[_registrationProgressing startAnimating];}- (void) updateRegistrationStatus:(NSNotification *) notification {[_registrationProgressing stopAnimating];if ([notification.userInfo objectForKey:@"error"]) {_registeringLabel.text = @"Error registering!";[self showAlert:@"Error registering with GCM" withMessage:notification.userInfo[@"error"]];} else {_registeringLabel.text = @"Registered!";NSString *message = @"Check the xcode debug console for the registration token that you can"" use with the demo server to send notifications to your device";[self showAlert:@"Registration Successful" withMessage:message];};}- (void) showReceivedMessage:(NSNotification *) notification {NSString *message = notification.userInfo[@"aps"][@"alert"];[self showAlert:@"Message received" withMessage:message];}- (void)showAlert:(NSString *)title withMessage:(NSString *) message{if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {// iOS 7.1 or earlierUIAlertView *alert = [[UIAlertView alloc] initWithTitle:titlemessage:messagedelegate:nilcancelButtonTitle:@"Dismiss"otherButtonTitles:nil];[alert show];} else {//iOS 8 or laterUIAlertController *alert =[UIAlertController alertControllerWithTitle:titlemessage:messagepreferredStyle:UIAlertControllerStyleAlert];UIAlertAction *dismissAction = [UIAlertAction actionWithTitle:@"Dismiss"style:UIAlertActionStyleDestructivehandler:nil];[alert addAction:dismissAction];[self presentViewController:alert animated:YES completion:nil];}}- (UIStatusBarStyle)preferredStatusBarStyle {return UIStatusBarStyleLightContent;}- (void)dealloc {[[NSNotificationCenter defaultCenter] removeObserver:self];}@endcs //podfile
12pod 'Google/CloudMessaging'cs 'App > Objective-C' 카테고리의 다른 글
Protocol (0) 2017.04.02 AVAudioSession (1) 2017.02.21 new와 alloc의 차이 (0) 2017.02.13 ARC(Automatic Reference Counting) (0) 2017.02.13 AppDelegate 함수 정리 (0) 2017.02.07