SDK do Google Analytics para iOS – migração para v3

Este guia descreve como fazer upgrade para a V3 do SDK do Google Analytics para iOS.

Visão rápida: o que há de novo na V3

As APIs na V3 foram refatoradas para serem mais consistentes em plataformas nativas e da Web. Todos os usuários da V2 devem observar estas alterações:

  • Os hits agora são enviados usando um único método send:(NSDictionary *)params.
  • O gerenciamento automático de sessões de clientes foi removido. O tempo limite da sessão pode ser configurado na interface de gerenciamento. Saiba mais.
  • O modo de depuração foi substituído por uma Logger.
  • Novo: uma sinalização dryRun foi adicionada para evitar que os dados enviados apareçam nos relatórios.
  • Novo: o suporte a moedas locais foi adicionado para iOS.

Para ver a lista completa das alterações, consulte o registro de alterações.

Antes de começar

Antes de começar a fazer upgrade para a v3, você precisará de:

Caminhos de upgrade

Para começar, selecione um caminho de upgrade para a v3 a partir da sua implementação atual:

Da v1.x para a v3

É recomendável que os usuários do SDK v1.x do Google Analytics para iOS sigam o Guia de primeiros passos v3 para começar a usar a v3.

Da v2.x para a v3

Os usuários da v2.x devem seguir estas etapas para fazer upgrade para a v3:

  1. Substitua todos os métodos de conveniência send<hit-type> pelo novo método send::
    // v2 (Old)
    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
    [tracker sendView:@"HomeScreen"];
    
    // v3
    id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
    // Set the screen name on the tracker so that it is used in all hits sent from this screen.
    [tracker set:kGAIScreenName value:@"Home Screen"];
    
    // Send a screenview.
    // [tracker send:[[GAIDictionaryBuilder createAppView]  build]];   // Previous V3 SDK versions.
    [tracker send:[[GAIDictionaryBuilder createScreenView]  build]];   // SDK Version 3.08 and up.
    
  2. O gerenciamento automático de sessões de clientes foi removido na v3. O tempo limite da sessão pode ser definido na interface de gerenciamento, e o padrão é 30 minutos. As sessões também podem ser iniciadas e interrompidas manualmente usando o parâmetro sessionControl. Saiba mais sobre o gerenciamento de sessões na v3.

  3. Os usuários do Acompanhamento automático de telas precisam substituir as referências a GAITrackedViewController.trackedViewName por GAITrackedViewController.screenName:
    // v2 (Old)
    #import "GAITrackedViewController.h"
    
    @implementation AboutViewController
    
    - (void)viewDidAppear:(BOOL)animated {
      [super viewDidAppear:animated];
      self.trackedViewName = @"About Screen";
    }
    
    // ... Rest of ViewController implementation.
    
    // v3
    #import "GAITrackedViewController.h"
    
    @implementation AboutViewController
    
    - (void)viewDidAppear:(BOOL)animated {
      [super viewDidAppear:animated];
      self.screenName = @"About Screen";
    }
    
    // ... Rest of ViewController implementation.
    
  4. O modo de depuração foi descontinuado. Use Logger:
    // v2 (Old)
    [GAI sharedInstance].debug = YES;
    
    // v3
    [[GAI sharedInstance].logger setLogLevel:kGAILogLevelVerbose];
    
  5. A propriedade GAI.useHttp foi removida. Para enviar hits usando HTTP em vez do HTTPS padrão, defina o parâmetro kGAIUseSecure em cada GAITracker:
    // v2 (Old)
    // AppDelegate.m
    
    #import AppDelegate.h
    #import GAI.h
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
        static NSString const *kGaPropertyId = @"UA-XXXX-Y";
        id tracker = [[GAI sharedInstance] trackerWithTrackingId:kGaPropertyId];
    
        // Send hits using HTTP (default=HTTPS).
        tracker.useHttps = NO;
    
    }
    
    // v3
    // AppDelegate.m
    
    #import AppDelegate.h
    #import GAI.h
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
        static NSString const *kGaPropertyId = @"UA-XXXX-Y";
        id tracker = [[GAI sharedInstance] trackerWithTrackingId:kGaPropertyId];
    
        // Send hits using HTTP (default=HTTPS).
        [tracker set:kGAIUseSecure value:[@NO stringValue]];
    
    }
    
  6. O SDK v3 não inicia mais uma nova sessão automaticamente quando o aplicativo é aberto. Se você quiser preservar esse comportamento da v2, precisará implementar sua própria lógica de controle de sessão quando um usuário iniciar o aplicativo:
  7. // AppDelegate.m
    
    #import AppDelegate.h
    #import GAI.h
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
        static NSString const *kGaPropertyId = @"UA-XXXX-Y";
        id tracker = [[GAI sharedInstance] trackerWithTrackingId:kGaPropertyId];
    
        // CAUTION: Setting session control directly on the tracker persists the
        // value across all subsequent hits, until it is manually set to null.
        // This should never be done in normal operation.
        //
        // [tracker set:kGAISessionControl value:@"start"];
    
        // Instead, send a single hit with session control to start the new session.
        [tracker send:[[[GAIDictionaryBuilder createEventWithCategory:@"UX"
                                                               action:@"appstart"
                                                                label:nil
                                                                value:nil] set:@"start" forKey:kGAISessionControl] build]];
    
    
  8. A configuração de desativação no nível do app não é mais mantida pelo SDK e precisa ser definida sempre que o app é iniciado (o padrão é NO). Saiba mais sobre como configurar a desativação no nível do aplicativo.

Referência

As seções a seguir fornecem exemplos de referências de como definir e enviar dados usando o SDK V3.

Envio de dados com dicionários na v3

Na V3, os dados são enviados com um único método send: que usa um NSDictionary dos campos e valores do Google Analytics como argumento. Uma classe de utilitário GAIDictionaryBuilder é fornecida para simplificar o processo de criação de hits:

id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];
[tracker set:kGAIScreenName value:@"Home Screen"];

// Previous V3 SDK versions.
// [tracker send:[[GAIDictionaryBuilder createAppView] setValue:@"Premium"  // Creates a Map of hit type 'AppView' (screenview) and set any additional fields.
//                                                     forKey:[customDimensionForIndex:1] build]; // Build and return the dictionary to the send method.

// SDK Version 3.08 and up.
[tracker send:[[GAIDictionaryBuilder createScreenView] setValue:@"Premium"  // Creates a Map of hit type 'ScreenView' and set any additional fields.
                                                       forKey:[customDimensionForIndex:1] build]; // Build and return the dictionary to the send method.

A classe GAIDictionaryBuilder pode ser usada para criar qualquer um dos tipos de hit compatíveis, como eventos:

id<GAITracker> tracker = [[GAI sharedInstance] defaultTracker];

[tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"ui_action"     // Event category (required)
                                                      action:@"button_press"  // Event action (required)
                                                       label:@"play"          // Event label
                                                       value:nil] build]];    // Event value

Saiba mais sobre o envio de dados na v3.

Definição de dados no rastreador na v3

Os valores também podem ser definidos diretamente em um GAITracker usando o método set:value:forKey. Os valores definidos diretamente são aplicados a todos os hits subsequentes desse GAITracker:

// Values set directly on a tracker apply to all subsequent hits.
[tracker set:kGAIScreenName value:@"Home Screen"];

// This screenview hit will include the screen name "Home Screen".
// [tracker send:[[GAIDictionaryBuilder createAppView] build]];   // Previous V3 SDK versions.
[tracker send:[[GAIDictionaryBuilder createScreenView] build]];   // SDK Version 3.08 and up.

// And so will this event hit.
[tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"ui_action"
                                                      action:@"button_press"
                                                       label:@"play"
                                                       value:nil] build]];

Para limpar um valor que foi definido em GAITracker, defina a propriedade como nil:

// Clear the previously-set screen name value.
[tracker set:kGAIScreenName
       value:nil];

// Now this event hit will not include a screen name value.
[tracker send:[[GAIDictionaryBuilder createEventWithCategory:@"ui_action"
                                                      action:@"button_press"
                                                       label:@"play"
                                                       value:nil] build]];

Saiba mais sobre a definição de dados na v3