ABOUT ME

-

Today
-
Yesterday
-
Total
-
  • GCM(Google Cloud Messaging)
    App/Objective-C 2017. 2. 24. 14:32


    GCM이란? 말그대로 구글에서 제공하는 알림 메시지 기능이다.

    서버측에서 데이터를 조작하여 앱에 알림바 형태로 제공할 수 있는 기능이며,

    이전에는 IOS에서는 APNS Android에서는 GCM을 이용하곤 했는데,

    몇년전에 통합되어 GCM으로 두 서비스 제공이 가능해졌다.


    //AppDelegate.h

    1
    2
    3
    4
    5
    6
    7
    8
    9
    10
    11
    12
    13
    #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;
     
    @end
     
    cs



    //AppDelegate.m

    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
    179
    180
    181
    182
    183
    184
    185
    186
    187
    188
    189
    190
    191
    192
    193
    194
    195
    196
    197
    198
    199
    200
    201
    202
    203
    204
    205
    206
    207
    208
    209
    210
    211
    212
    213
    214
    215
    216
    217
    218
    219
    220
    221
    222
    223
    224
    225
    226
    227
    228
    229
    230
    231
    //
    //  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;
    @end
     
    NSString *const SubscriptionTopic = @"/topics/global";
     
    @implementation AppDelegate
     
    // [START register_for_remote_notifications]
    - (BOOL)application:(UIApplication *)application
          didFinishLaunchingWithOptions:(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 file
      NSError* configureError;
      [[GGLContext sharedInstance] configureWithError:&configureError];
      NSAssert(!configureError, @"Error configuring Google services: %@", configureError);
      _gcmSenderID = [[[GGLContext sharedInstance] configuration] gcmSenderID];
      // Register for remote notifications
      if (floor(NSFoundationVersionNumber) <= NSFoundationVersionNumber_iOS_7_1) {
        // iOS 7.1 or earlier
        UIRemoteNotificationType 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.registrationKey
                                                              object:nil
                                                            userInfo:userInfo];
        } else {
          NSLog(@"Registration to GCM failed with error: %@", error.localizedDescription);
          NSDictionary *userInfo = @{@"error":error.localizedDescription};
          [[NSNotificationCenter defaultCenter] postNotificationName:weakSelf.registrationKey
                                                              object:nil
                                                            userInfo:userInfo];
        }
      };
      return YES;
    }
     
    - (void)subscribeToTopic {
      // If the app has a registration token and is connected to GCM, proceed to subscribe to the
      // topic
      if (_registrationToken && _connectedToGCM) {
        [[GCMPubSub sharedInstance] subscribeWithToken:_registrationToken
                                                 topic:SubscriptionTopic
                                               options:nil
                                               handler:^(NSError *error) {
                                                 if (error) {
                                                   // Treat the "already subscribed" error more gently
                                                   if (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 *)application
        didRegisterForRemoteNotificationsWithDeviceToken:(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:_gcmSenderID
                                                          scope:kGGLInstanceIDScopeGCM
                                                        options:_registrationOptions
                                                        handler:_registrationHandler];
      // [END get_gcm_reg_token]
    }
     
    // [START receive_apns_token_error]
    - (void)application:(UIApplication *)application
        didFailToRegisterForRemoteNotificationsWithError:(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:_registrationKey
                                                          object:nil
                                                        userInfo:userInfo];
    }
     
    // [START ack_message_reception]
    - (void)application:(UIApplication *)application
        didReceiveRemoteNotification:(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:_messageKey
                                                          object:nil
                                                        userInfo:userInfo];
      // [END_EXCLUDE]
    }
     
    - (void)application:(UIApplication *)application
        didReceiveRemoteNotification:(NSDictionary *)userInfo
        fetchCompletionHandler:(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:_messageKey
                                                          object:nil
                                                        userInfo: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:_gcmSenderID
                                                          scope:kGGLInstanceIDScopeGCM
                                                        options:_registrationOptions
                                                        handler:_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

    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
    //
    //  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:self
                                               selector:@selector(updateRegistrationStatus:)
                                                   name:appDelegate.registrationKey
                                                 object:nil];
      [[NSNotificationCenter defaultCenter] addObserver:self
                                               selector:@selector(showReceivedMessage:)
                                                   name:appDelegate.messageKey
                                                 object: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 earlier
        UIAlertView *alert = [[UIAlertView alloc] initWithTitle:title
                                                        message:message
                                                       delegate:nil
                                              cancelButtonTitle:@"Dismiss"
                                              otherButtonTitles:nil];
        [alert show];
      } else {
        //iOS 8 or later
        UIAlertController *alert =
            [UIAlertController alertControllerWithTitle:title
                                                message:message
                                         preferredStyle:UIAlertControllerStyleAlert];
     
        UIAlertAction *dismissAction = [UIAlertAction actionWithTitle:@"Dismiss"
                                                                style:UIAlertActionStyleDestructive
                                                              handler:nil];
     
        [alert addAction:dismissAction];
        [self presentViewController:alert animated:YES completion:nil];
      }
    }
     
    - (UIStatusBarStyle)preferredStatusBarStyle {
      return UIStatusBarStyleLightContent;
    }
     
    - (void)dealloc {
      [[NSNotificationCenter defaultCenter] removeObserver:self];
    }
     
    @end
    cs



    //podfile

    1
    2
     
    pod '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
Designed by Tistory.