どこのサイトを見てもAWS SNSの利用方法に関して、GUIを使ったものや、サーバーを介した方法しか紹介ばかりだったので、AWS SDKから直接SNSにEndpointを登録する方法をご紹介します。
サーバーを介さずにEndpointを登録出来るため、小さなアプリの場合はわざわざサーバーを建てなくてもAWSでPush機能が完結します。
そもそもSNSとは
SNSとはSimple Notification Serviceの略で、ざっくり言うと「簡単にPush通知のサーバーが建てれますよ」というサービスです。
SNSでは"$1/100万Push"という価格も魅力的です。
はじめに
ほかのサイトでもかなり紹介されているので、本記事ではSNSにアプリケーションを建てる部分は完全に省略します。
ざっくりな流れとしてはiOS Dev CenterでPush Notification用の証明書を取得して、その鍵情報をキーチェーンアクセスでp12型に変換します。あとはSNSのコンソールでCreateAppして貼り付けてあげれば完了です。
まずはDeviceTokenを取得
アプリでPush通知を扱う際はapplication:didFinishLaunchingWithOptions:メソッドにPush通知を利用する事を登録する必要があります。
[[UIApplication sharedApplication] registerForRemoteNotificationTypes:
(UIRemoteNotificationTypeBadge|
UIRemoteNotificationTypeSound|
UIRemoteNotificationTypeAlert)];
すると以下のメソッドが呼ばれるようになるのでその中でPush通知をサーバーに登録していきましょう。
- (void)application:(UIApplication *)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData *)deviceToken
deviceTokenはNSData型な上、そのままString型に変換すると前後に<>が付くだけで無く、空白が入ってしまうので適当に整形する必要があります。
これは人によって好みがあると思うので、適宜整形して下さい。
NSString* token = [[[[deviceToken description] stringByReplacingOccurrencesOfString: @"<" withString: @""]
stringByReplacingOccurrencesOfString: @">" withString: @""]
stringByReplacingOccurrencesOfString: @" " withString: @""];
NSLog(@"%@",token);
これでdeviceTokenが取得出来たかと思います。
SNSにデータを送信する
AWSSNSをクラスを利用する際はAWSSNS.hをインポートしてください。
#import <AWSiOSSDKv2/AWSSNS.h>
また、 AWSCredentialsProviderプロトコルを実装し、accessKeyとsecretKeyプロパティを実装して下さい
@interface AppDelegate : UIResponder <UIApplicationDelegate,AWSCredentialsProvider>
.
.
.
@property (nonatomic, strong) NSString *accessKey;
@property (nonatomic, strong) NSString *secretKey;
@end
あとはAWSSNSクラスのインスタンスを作り、その際にConfigurationにselfを指定する事で以下のように実装することができます。
もちろん他のクラスにアクセスキーなどをもたせればgitなどでの管理も楽になりますね。
登録したいデバイスの情報はAWSSNSCreatePlatformEndpointInputクラスのインスタンスを作成してプロパティに値を入れることで設定が可能です。
self.accessKey = @"アクセスキー";
self.secretKey = @"シークレットキー";
AWSSNS* client = [[AWSSNS alloc]initWithConfiguration:
[AWSServiceConfiguration configurationWithRegion:AWSRegionAPNortheast1 credentialsProvider:self]];
AWSSNSCreatePlatformEndpointInput* input = [AWSSNSCreatePlatformEndpointInput new];
input.customUserData = @"ユーザー情報";
input.token = token;
input.platformApplicationArn = @"arn:aws:sns:ap-northeast-1:数字:app/APNS_SANDBOX/アプリ名";
[client createPlatformEndpoint:input];
実際にSNSのコンソールを開いてみてデバイスの情報が入っている事を確認したらPublishして試してみてください。