Регистрация устройств iOS для использования с Amazon SNS (APNS) через Amazon Anonymous TVM

Подобные вопросы появляются несколько раз на StackOverflow, но решения для Amazon SNS нет.

В этой документации указано, что регистрация устройств для Amazon SNS (APNS) можно оформить через торговый автомат для анонимных токенов. Эта документация содержит шаблон для развертывания, которое я использовал, затем этот пример кода указывает клиент iOS, который демонстрирует его использование. Однако ни в источнике конфигурации шаблона, ни в примере клиента iOS я не вижу, как TVM связывается с приложением SNS для создания записей устройств (называемых конечными точками). Любые идеи, где это происходит?


person Oh Danny Boy    schedule 21.04.2014    source источник


Ответы (1)


Оказывается, ссылка связана на стороне клиента. Решение было следующим:

Include:

AWSRuntime.framework
AWSSecurityTokenService.framework
AWSSNS.framework


#define SNS_PLATFORM_APPLICATION_ARN @"Insert ARN here"
#define TOKEN_VENDING_MACHINE_URL @"Insert vending machine url, found in output tab"
#define USE_SSL 1

#pragma mark - Amazon TVM


+ (void)initSNS
{
    AmazonCredentials *credentials = [AmazonKeyChainWrapper getCredentialsFromKeyChain];

    sns = [[AmazonSNSClient alloc] initWithCredentials:credentials];
    sns.endpoint = [AmazonEndpoints snsEndpoint:US_WEST_2];

    [[UIApplication sharedApplication] registerForRemoteNotificationTypes:
     UIRemoteNotificationTypeBadge |
     UIRemoteNotificationTypeAlert |
     UIRemoteNotificationTypeSound];
}

+ (AmazonTVMClient *)tvm
{
    if (tvm == nil) {
        tvm = [[AmazonTVMClient alloc] initWithEndpoint:TOKEN_VENDING_MACHINE_URL useSSL:USE_SSL];
    }

    return tvm;
}

+ (bool)hasCredentials
{
    return ![TOKEN_VENDING_MACHINE_URL isEqualToString:@"CHANGE ME"];
}

+ (Response *)validateCredentials
{
    Response *ableToGetToken = [[Response alloc] initWithCode:200 andMessage:@"OK"];

    if ([AmazonKeyChainWrapper areCredentialsExpired]) {

        @synchronized(self)
        {
            if ([AmazonKeyChainWrapper areCredentialsExpired]) {

                ableToGetToken = [[self tvm] anonymousRegister];

                if ( [ableToGetToken wasSuccessful])
                {
                    ableToGetToken = [[self tvm] getToken];

                    if ( [ableToGetToken wasSuccessful])
                    {
                        [AppDelegate initSNS];
                    }
                }
            }
        }
    }
    else
    {
        [AppDelegate initSNS];
    }

    return ableToGetToken;
}

#pragma mark - Push Notification

- (void)application:(UIApplication *)application didReceiveRemoteNotification:(NSDictionary *)userInfo
{
    application.applicationIconBadgeNumber = 0;
    NSString *msg = [NSString stringWithFormat:@"%@", userInfo];
    NSLog( @"%@", msg );

    UIAlertView *alertView = [[UIAlertView alloc] initWithTitle:@"Message Received" message:[NSString stringWithFormat:@"%@", msg]delegate:self cancelButtonTitle:@"OK" otherButtonTitles:nil];
    [alertView show];
}


-(NSString*)deviceTokenAsString:(NSData*)deviceTokenData
{
    NSString *rawDeviceTring = [NSString stringWithFormat:@"%@", deviceTokenData];
    NSString *noSpaces = [rawDeviceTring stringByReplacingOccurrencesOfString:@" " withString:@""];
    NSString *tmp1 = [noSpaces stringByReplacingOccurrencesOfString:@"<" withString:@""];

    return [tmp1 stringByReplacingOccurrencesOfString:@">" withString:@""];
}


- (void)application:(UIApplication*)application didRegisterForRemoteNotificationsWithDeviceToken:(NSData*)deviceToken
{
    NSLog( @"Submit the device token [%@] to SNS to receive notifications.", deviceToken );
    SNSCreatePlatformEndpointRequest *platformEndpointRequest = [SNSCreatePlatformEndpointRequest new];
    platformEndpointRequest.customUserData =  @"Here's the custom data for the user.";
    platformEndpointRequest.token = [self deviceTokenAsString:deviceToken];
    platformEndpointRequest.platformApplicationArn = SNS_PLATFORM_APPLICATION_ARN;

    [sns createPlatformEndpoint:platformEndpointRequest];
}
person Oh Danny Boy    schedule 22.04.2014