Objective-C 시작 가이드

이 개발자 가이드에서는 Google 태그 관리자를 사용할 수 있습니다.

소개

Google 태그 관리자를 사용하면 개발자가 구성을 변경할 수 있습니다. Google 태그 관리자를 이용하여 모바일 애플리케이션에서 애플리케이션 바이너리를 다시 빌드하고 앱에 다시 제출할 필요 없이 있습니다.

이는 구성 값을 관리하는 데 유용합니다. 나중에 변경해야 할 수도 있는 플래그 또는 플래그를 포함:

  • 다양한 UI 설정 및 표시 문자열
  • 애플리케이션에 게재되는 광고의 크기, 위치 또는 유형
  • 게임 설정

구성 값은 런타임에 규칙을 사용하여 평가할 수도 있습니다. 동적 구성을 사용할 수 있습니다.

  • 화면 크기를 사용하여 광고 배너 크기 결정하기
  • 언어 및 위치를 사용하여 UI 요소 구성

또한 Google 태그 관리자를 이용하면 추적 태그를 동적으로 구현할 수 있습니다. 픽셀 등이 있습니다. 개발자는 중요한 이벤트를 데이터에 푸시하고 나중에 실행할 추적 태그 또는 픽셀을 결정합니다. 태그 관리자에서 현재 지원하는 태그는 다음과 같습니다.

  • Google 모바일 앱 애널리틱스
  • 맞춤 함수 호출 태그

시작하기 전에

이 시작 가이드를 사용하려면 다음 항목이 필요합니다.

Google 태그 관리자를 처음 사용하는 경우에는 <ph type="x-smartling-placeholder"></ph> 컨테이너, 매크로, 규칙에 대해 자세히 알아본 후 (고객센터) 이 가이드를 계속 진행하세요.

시작하기

이 섹션에서는 개발자에게 일반적인 태그 관리자 워크플로를 안내합니다.

  1. 프로젝트에 Google 태그 관리자 SDK 추가
  2. 기본 컨테이너 값 설정
  3. 컨테이너 열기
  4. 컨테이너에서 구성 값 가져오기
  5. DataLayer에 이벤트 푸시
  6. 미리보기 및 컨테이너 게시하기

1. 프로젝트에 Google 태그 관리자 SDK 추가

Google 태그 관리자 SDK를 사용하려면 먼저 libGoogleAnalyticsServices.aLibrary의 Google 태그 관리자 (GTM) 헤더 파일 SDK 패키지의 디렉터리를 프로젝트에 가져옵니다.

다음으로 애플리케이션 타겟의 연결된 라이브러리에 다음을 추가합니다( 없는 경우:

  • CoreData.framework
  • SystemConfiguration.framework
  • libz.dylib
  • libsqlite3.dylib
  • libGoogleAnalyticsServices.a

애플리케이션이 광고주 (IDFA)와 추적 플래그를 Google 태그 관리자 SDK 매크로를 사용하는 경우 다음과 같은 추가 라이브러리도 연결해야 합니다.

  • libAdIdAccess.a
  • AdSupport.framework
를 통해 개인정보처리방침을 정의할 수 있습니다.

2. 프로젝트에 기본 컨테이너 파일 추가

Google 태그 관리자는 애플리케이션을 처음 실행할 때 기본 컨테이너를 사용합니다. 기본값 컨테이너는 앱이 최신 컨테이너를 통해 새 컨테이너를 가져올 수 있을 때까지 네트워크에 속합니다.

애플리케이션에 기본 컨테이너 바이너리를 다운로드하고 추가하려면 다음 단계를 따르세요.

  1. Google 태그 관리자 웹 인터페이스에 로그인합니다.
  2. 다운로드할 컨테이너의 버전을 선택합니다.
  3. 다운로드 버튼을 클릭하여 컨테이너 바이너리를 검색합니다.
  4. 바이너리 파일을 '지원 파일'로 이동한 다음 생성합니다.

기본 파일 이름은 컨테이너 ID (예: GTM-1234)여야 합니다. kubectl 명령어 바이너리 파일을 다운로드한 경우에는 파일 이름에서 버전 접미사를 삭제해야 합니다. 올바른 이름 지정 규칙을 따르는지 확인하세요

바이너리 파일을 사용하는 것이 좋지만 컨테이너에 규칙이나 태그가 포함되어 있지 않다면 간단한 속성 목록 또는 JSON 파일을 대신 사용하세요. 파일은 기본 번들에 있어야 하며 이름 지정 규칙(<Container_ID>.<plist|json>)을 사용합니다. 예를 들어 컨테이너 ID가 GTM-1234이면 라는 속성 목록 파일에 기본 컨테이너 값이 포함되어 있습니다. GTM-1234.plist입니다.

3. 컨테이너 열기

컨테이너에서 값을 가져오려면 먼저 애플리케이션에서 합니다 컨테이너를 열면 디스크에서 로드됩니다 (가능한 경우). (필요한 경우) 네트워크에서 이를 요청합니다.

iOS에서 컨테이너를 여는 가장 쉬운 방법은 openContainerWithId:tagManager:openType:timeout:notifier:를 사용해야 합니다.

// MyAppDelegate.h
// This example assumes this file is using ARC.
#import <UIKit/UIKit.h>

@class TAGManager;
@class TAGContainer;

@interface MyAppDelegate : UIResponder <UIApplicationDelegate>

@property (nonatomic, strong) TAGManager *tagManager;
@property (nonatomic, strong) TAGContainer *container;

@end


// MyAppDelegate.m
// This example assumes this file is using ARC.
#import "MyAppDelegate.h"
#import "TAGContainer.h"
#import "TAGContainerOpener.h"
#import "TAGManager.h"

@interface MyAppDelegate ()<TAGContainerOpenerNotifier>
@end

@implementation MyAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  self.tagManager = [TAGManager instance];

  // Optional: Change the LogLevel to Verbose to enable logging at VERBOSE and higher levels.
  [self.tagManager.logger setLogLevel:kTAGLoggerLogLevelVerbose];

  /*
   * Opens a container.
   *
   * @param containerId The ID of the container to load.
   * @param tagManager The TAGManager instance for getting the container.
   * @param openType The choice of how to open the container.
   * @param timeout The timeout period (default is 2.0 seconds).
   * @param notifier The notifier to inform on container load events.
   */
  [TAGContainerOpener openContainerWithId:@"GTM-XXXX"   // Update with your Container ID.
                               tagManager:self.tagManager
                                 openType:kTAGOpenTypePreferFresh
                                  timeout:nil
                                 notifier:self];

  // Method calls that don't need the container.

  return YES;
}

// TAGContainerOpenerNotifier callback.
- (void)containerAvailable:(TAGContainer *)container {
  // Note that containerAvailable may be called on any thread, so you may need to dispatch back to
  // your main thread.
  dispatch_async(dispatch_get_main_queue(), ^{
    self.container = container;
  });
}

// The rest of your app delegate implementation.
드림

4. 컨테이너에서 구성 값 가져오기

컨테이너가 열리면 다음을 사용하여 구성 값을 가져올 수 있습니다. <type>ForKey: 메서드:

// Retrieving a configuration value from a Tag Manager Container.

MyAppDelegate *appDelegate = (MyAppDelegate *)[[UIApplication sharedApplication] delegate];
TAGContainer *container = appDelegate.container;

// Get the configuration value by key.
NSString *title = [container stringForKey:@"title_string"];

존재하지 않는 키로 요청한 경우 해당하는 기본값이 반환됩니다. 다음과 같습니다.

// Empty keys will return a default value depending on the type requested.

// Key does not exist. An empty string is returned.
NSString subtitle = [container stringForKey:@"Non-existent-key"];
[subtitle isEqualToString:@""]; // Evaluates to true.

5. DataLayer에 값 푸시하기

데이터 레이어는 터치와 같은 앱에 대한 런타임 정보를 활성화하는 지도입니다. 태그 관리자 매크로 및 태그에서 사용할 수 있도록 하기 위해 있습니다

예를 들어 화면 조회수에 대한 정보를 데이터 영역 지도로 푸시하면 전환 픽셀을 실행하도록 태그 관리자 웹 인터페이스에서 태그를 설정할 수 있습니다. 화면 조회수에 대한 응답으로 통화를 추적하거나 앱에 직접 코딩할 수 있습니다.

이벤트가 push:를 사용하여 DataLayer로 푸시됨

//
//  ViewController.m
//  Pushing an openScreen event with a screen name into the data layer.
//

#import "MyAppDelegate.h"
#import "TAGDataLayer.h"
#import "ViewController.h"

@implementation ViewController

- (void)viewDidAppear:(BOOL)animated {
    [super viewDidAppear:animated];

    // The container should have already been opened, otherwise events pushed to
    // the data layer will not fire tags in that container.
    TAGDataLayer *dataLayer = [TAGManager instance].dataLayer;

    [dataLayer push:@{@"event": @"openScreen", @"screenName": @"Home Screen"}];
}

// Rest of the ViewController implementation

@end

이제 웹 인터페이스에서 Google 애널리틱스 태그와 같은 태그를 만들 수 있습니다. 다음 규칙을 만들어 각 화면 조회에 대해 실행할 수 있습니다. 이(가) 'openScreen'과 같습니다. 화면 이름을 전달하는 방법 추가하려면 'screenName' 키를 누릅니다. 또한 태그를 만들어 (예: Google Ads 전환 픽셀)를 사용하여 특정 화면 조회에 대해서만 실행되도록 하려면 이(가) 'openScreen'과 같은 규칙 만들기 && 이(가) 'ConfirmationScreen'과 같습니다.

6. 미리보기 및 컨테이너 게시

매크로 값은 항상 현재 게시된 버전과 일치합니다. 최신 버전의 컨테이너를 게시하기 전에 미리 볼 수 있습니다. 임시 컨테이너에 있습니다

컨테이너를 미리 보려면 Google 태그 관리자 웹 인터페이스를 선택합니다. 선택한 다음 Preview를 선택합니다. 잠시만 기다려 주세요 이 미리보기 URL은 이후 단계에서 필요하므로

<ph type="x-smartling-placeholder">
</ph> 미리보기 URL은 태그의 미리보기 창에서 확인할 수 있습니다.
           관리자 웹 인터페이스
그림 1: 미리보기 URL을 태그 관리자 웹 인터페이스

컨테이너 미리보기를 사용 설정하려면 앱에 코드를 추가해야 합니다. 위임 구현 파일을 만들고 Google 태그 관리자 미리보기 URL을 정의합니다. 스키마의 이름을 지정합니다.

먼저, 굵게 표시된 다음 코드 스니펫을 앱 대리자 파일에 추가합니다.

@implementation MyAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {

  self.tagManager = [TAGManager instance];
  
  // Add the code in bold below to preview a Google Tag Manager container.
  // IMPORTANT: This code must be called before the container is opened.
  NSURL *url = [launchOptions valueForKey:UIApplicationLaunchOptionsURLKey];
  if (url != nil) {
    [self.tagManager previewWithUrl:url];
  }
  
  id<TAGContainerFuture> future =
      [TAGContainerOpener openContainerWithId:@"GTM-XXXX"    // Placeholder Container ID.
                                   tagManager:self.tagManager
                                     openType:kTAGOpenTypePreferNonDefault
                                      timeout:nil];

  // The rest of your method implementation.

  self.container = [future get];

  return YES;
}


// Add the code in bold below preview a Google Tag Manager container.
- (BOOL)application:(UIApplication *)application
            openURL:(NSURL *)url
  sourceApplication:(NSString *)sourceApplication
         annotation:(id)annotation {

  if ([self.tagManager previewWithUrl:url]) {
    return YES;
  }

  // Code to handle other urls.
  return NO;
}

그런 다음 아래의 URL 식별자와 URL 스키마를 애플리케이션 속성 목록 파일의 URL 유형 키:

URL identifier: your.package_name
URL scheme: tagmanager.c.your.package.name
드림 <ph type="x-smartling-placeholder">
</ph> 애플리케이션의
                속성 목록 파일을 참조하세요.
그림 3: 태그 관리자 미리보기 URL 스키마 추가 를 애플리케이션의 속성 목록 파일에 추가합니다.
를 통해 개인정보처리방침을 정의할 수 있습니다.

에뮬레이터나 실제 기기에서 링크를 열어 앱에서 컨테이너 초안을 미리 볼 수 있습니다

초안 구성 값을 애플리케이션, 컨테이너를 게시합니다.

고급 구성

모바일용 Google 태그 관리자에는 다양한 고급 구성이 있습니다. 매개변수를 사용하여 런타임 조건에 따라 값을 선택할 수 있는 수동으로 컨테이너를 새로고침하고, 컨테이너를 여는 데 사용되는 추가 옵션을 살펴보겠습니다 다음 섹션에서는 가장 일반적인 고급 기능 몇 가지를 구성할 수 있습니다

컨테이너 열기를 위한 고급 옵션

Google 태그 관리자 SDK는 보다 세밀하게 제어할 수 있는 컨테이너도 있습니다.

openContainerById:callback:

openContainerById:callback:는 애플리케이션을 여는 데 사용되는 가장 낮은 수준이며 가장 유연한 API입니다. 있습니다 기본 컨테이너와 함께 즉시 반환되며 저장된 컨테이너가 없는 경우 디스크나 네트워크에서 비동기식으로 저장된 컨테이너가 최신 상태가 아닌 경우(12시간 초과)

@interface ContainerCallback : NSObject<TAGContainerCallback>

@end

@implementation ContainerCallback

/**
 * Called before the refresh is about to begin.
 *
 * @param container The container being refreshed.
 * @param refreshType The type of refresh which is starting.
 */
- (void)containerRefreshBegin:(TAGContainer *)container
                  refreshType:(TAGContainerCallbackRefreshType)refreshType {
  // Notify UI that container refresh is beginning.
}

/**
 * Called when a refresh has successfully completed for the given refresh type.
 *
 * @param container The container being refreshed.
 * @param refreshType The type of refresh which completed successfully.
 */
- (void)containerRefreshSuccess:(TAGContainer *)container
                    refreshType:(TAGContainerCallbackRefreshType)refreshType {
  // Notify UI that container is available.
}

/**
 * Called when a refresh has failed to complete for the given refresh type.
 *
 * @param container The container being refreshed.
 * @param failure The reason for the refresh failure.
 * @param refreshType The type of refresh which failed.
 */
- (void)containerRefreshFailure:(TAGContainer *)container
                        failure:(TAGContainerCallbackRefreshFailure)failure
                    refreshType:(TAGContainerCallbackRefreshType)refreshType {
  // Notify UI that container request has failed.
}
@end

로드하는 동안 문제 openContainerById:callback:개 코드가 호출될 때를 알 수 있도록 여러 수명 주기 콜백에 그리고 로드 요청의 실패 또는 성공 여부 및 컨테이너가 궁극적으로 디스크 또는 네트워크에서 로드되었기 때문입니다.

애플리케이션이 기본값을 사용할 수 없는 경우에는 이러한 콜백을 사용하여 저장된 네트워크 또는 네트워크 아웃렛을 컨테이너를 로드하면 됩니다 저장된 이미지나 이메일 주소를 애플리케이션을 처음 실행하고 해당 앱에 아무런 네트워크 연결입니다.

openContainerById:callback:가 다음 enum를 전달합니다. 값을 다음 콜백에 대한 인수로 사용하세요.

RefreshType

설명
kTAGContainerCallbackRefreshTypeSaved 새로고침 요청이 로컬에 저장된 컨테이너를 로드하고 있습니다.
kTAGContainerCallbackRefreshTypeNetwork 새로고침 요청이 네트워크를 통해 컨테이너를 로드하고 있습니다.

RefreshFailure

설명
kTAGContainerCallbackRefreshFailureNoSavedContainer 저장된 컨테이너가 없습니다.
kTAGContainerCallbackRefreshFailureIoError I/O 오류로 인해 컨테이너를 새로고침할 수 없습니다.
kTAGContainerCallbackRefreshFailureNoNetwork 사용할 수 있는 네트워크 연결이 없습니다.
kTAGContainerCallbackRefreshFailureNetworkError 네트워크 오류가 발생했습니다.
kTAGContainerCallbackRefreshFailureServerError 서버에 오류가 발생했습니다.
kTAGContainerCallbackRefreshFailureUnknownError 분류할 수 없는 오류가 발생했습니다.

기본이 아닌 새로운 컨테이너를 여는 방법

TAGContainerOpener 래핑 openContainerById:callback: 및 컨테이너를 여는 편리한 두 가지 메서드를 제공합니다. openContainerWithId:tagManager:openType:timeout:notifier:openContainerWithId:tagManager:openType:timeout:입니다.

이러한 각 메서드는 기본값이 아닌 값 또는 컨테이너 이미지를 새로 만들 수 있습니다

kTAGOpenTypePreferNonDefault는 대부분의 애플리케이션에 권장되며 주어진 컨테이너 내에서 기본이 아닌 첫 번째 사용 가능한 컨테이너를 반환하려고 시도합니다. 디스크 또는 네트워크의 제한 시간(컨테이너가 더 크더라도) 합니다. 비활성으로 저장된 컨테이너를 반환할 경우에도 비동기 네트워크 요청을 전송해야 합니다. kTAGOpenTypePreferNonDefault를 사용하는 경우 사용 가능한 다른 컨테이너가 없거나 제한 시간이 초과되었습니다.

kTAGOpenTypePreferFresh가 다음 위치에서 새 컨테이너를 반환하려고 시도합니다. 디스크 또는 네트워크를 모두 실행할 수 있습니다 네트워크가 외부 IP 주소 없이도 연결할 수 없거나 제한 시간이 초과되었습니다.

kTAGOpenTypePreferFresh 사용은 권장되지 않습니다. 더 긴 요청 시간이 사용자 환경에 현저하게 영향을 미칠 수 있는 곳에서는 예를 들어 UI 플래그 또는 표시 문자열을 사용하면 됩니다 또한 언제든지 TAGContainer::refresh 네트워크 컨테이너 요청을 강제할 수 있습니다

이러한 편리한 메서드는 모두 비블로킹입니다. openContainerWithId:tagManager:openType:timeout:TAGContainerFuture 객체: 이 객체의 get 메서드가 로드되는 즉시 TAGContainer (그때까지 차단됨) openContainerWithId:tagManager:openType:timeout:notifier: 메서드는 단일 콜백을 사용합니다. 컨테이너를 사용할 수 있을 때 호출됩니다. 두 메서드 모두 기본 제한 시간은 다음과 같습니다. 2.0

규칙을 사용하여 런타임에 매크로 평가하기

컨테이너는 규칙을 사용하여 런타임에 값을 평가할 수 있습니다. 규칙은 다음을 기반으로 합니다. 기기 언어, 플랫폼 또는 기타 매크로 값과 같은 기준을 충족해야 합니다. 대상 예를 들어 규칙을 사용하여 언어를 변경할 수 있습니다 이는 다음 규칙을 따릅니다.

<ph type="x-smartling-placeholder">
</ph> 규칙은 다음 위치에서 기기 언어에 따라 표시 문자열을 선택하는 데 사용됩니다.
            runtime: language는 es와 같습니다. 이 규칙은 사전 정의된 언어를 사용합니다.
            매크로와 2자리 ISO 639-1 언어 코드를 포함합니다.
그림 1: 기기에만 값 수집 매크로를 사용 설정하는 규칙 추가 스페인어를 사용하도록 구성되어 있습니다

그런 다음 각 언어에 대한 값 수집 매크로를 만들고 규칙을 만들어 적절한 언어 코드를 삽입합니다. 이 컨테이너가 게시된 후에 애플리케이션이 문자열에 쓸 수 있습니다.

기본 컨테이너에 규칙이 필요한 경우 바이너리 컨테이너 파일을 있습니다

<ph type="x-smartling-placeholder"></ph> 규칙 구성에 대해 자세히 알아보기 (고객센터)

바이너리 기본 컨테이너 파일

규칙이 필요한 기본 컨테이너는 바이너리 컨테이너 파일을 사용해야 합니다. 속성 목록 파일 또는 JSON 대신 파일을 기본 컨테이너로 설정합니다. 바이너리 컨테이너는 컨테이너 이미지를 결정하는 데 매크로 값을 사용하는 대신 속성 목록 또는 JSON 파일은 포함되지 않습니다.

Google 태그 관리자 웹에서 바이너리 컨테이너 파일을 다운로드할 수 있습니다. 인터페이스와 이 이름 지정 규칙에 따라 기본 애플리케이션 번들에 추가해야 합니다. GTM-XXXX, 여기서 파일 이름은 있습니다.

속성 목록 파일 또는 JSON 파일이 바이너리 컨테이너 파일이 있는 경우 SDK는 바이너리 컨테이너를 사용합니다. 파일을 기본 컨테이너로 설정합니다.

함수 호출 매크로 사용

함수 호출 매크로는 지정할 수도 있습니다 함수 호출 매크로는 다음과 같은 Google 태그 관리자 규칙에 런타임 값을 통합할 수 있습니다. 구성된 기기 언어 및 통화를 지정할 수 있습니다.

함수 호출 매크로를 구성하는 방법은 다음과 같습니다.

  1. Google 태그 관리자 웹 인터페이스에서 함수 호출 매크로를 정의합니다. 인수는 키-값 쌍으로 구성할 수도 있습니다.
  2. TAGFunctionCallMacroHandler를 구현하는 핸들러 정의 프로토콜:
    // MyFunctionCallMacroHandler.h
    #import "TAGContainer.h"
    
    // The function name field of the macro, as defined in the Google Tag Manager
    // web interface.
    extern NSString *const kMyMacroFunctionName;
    
    @interface MyFunctionCallMacroHandler : NSObject<TAGFunctionCallMacroHandler>
    
    @end
    
    
    // MyFunctionCallMacroHandler.m
    #import "MyFunctionCallMacroHandler.h"
    
    // Corresponds to the function name field in the Google Tag Manager interface.
    NSString *const kMyMacroFunctionName = @"myConfiguredFunctionName";
    
    @implementation MacroHandler
    
    - (id)valueForMacro:(NSString *)functionName parameters:(NSDictionary *)parameters {
    
      if ([functionName isEqualToString:kMyMacroFunctionName]) {
        // Process and return the calculated value of this macro accordingly.
        return macro_value;
      }
      return nil;
    }
    
    @end
  3. TAGContainer::registerFunctionCallMacroHandler:forMacro: 및 함수 이름을 사용하여 핸들러를 등록합니다. 를 사용합니다.
  4. //
    // MyAppDelegate.h
    //
    #import <UIKit/UIKit.h>
    
    @interface MyAppDelegate : UIResponder <UIApplicationDelegate>
    
    @end
    
    
    //
    // MyAppDelegate.m
    //
    #import "MyAppDelegate.h"
    #import "MyFunctionCallMacroHandler.h"
    #import "TAGContainer.h"
    #import "TAGContainerOpener.h"
    #import "TAGManager.h"
    
    @implementation MyAppDelegate
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions
    {
      // Open the container.
      id<TAGContainerFuture> future =
          [TAGContainerOpener openContainerWithId:@"GTM-XXXX"    // Placeholder Container ID.
                                       tagManager:[TAGManager instance]
                                         openType:kTAGOpenTypePreferNonDefault
                                          timeout:nil];
    
      // Method calls that don't need the container.
    
      self.container = [future get];
    
      // Register a function call macro handler using the macro name defined
      // in the Google Tag Manager web interface.
      [self.container registerFunctionCallMacroHandler:[[MyFunctionCallMacroHandler alloc] init]
                                              forMacro:kMyMacroFunctionName];
    }
    
    @end

함수 호출 태그 사용

함수 호출 태그를 사용하면 언제든지 사전 등록된 함수를 실행할 수 있습니다. 이벤트가 데이터 영역으로 푸시되고 태그 규칙이 true로 평가됩니다.

함수 호출 태그를 구성하는 방법은 다음과 같습니다.

  1. Google 태그 관리자 웹 인터페이스에서 함수 호출 태그를 정의합니다. 인수는 키-값 쌍으로 구성할 수도 있습니다.
  2. TAGFunctionCallTagHandler 프로토콜을 구현합니다.
    //
    // MyFunctionCallTagHandler.h
    //
    
    #import "TAGContainer.h"
    
    extern NSString *const kMyTagFunctionName;
    
    @interface MyFunctionCallTagHandler : NSObject<TAGFunctionCallTagHandler>
    
    @end
    
    
    //
    // MyFunctionCallTagHandler.m
    //
    
    // Corresponds to the function name field in the Google Tag Manager interface.
    NSString *const kMyTagFunctionName = @"myConfiguredFunctionName";
    
    @implementation MyFunctionCallTagHandler
    
    /**
     * This method will be called when any custom tag's rule(s) evaluate to true and
     * should check the functionName and process accordingly.
     *
     * @param functionName corresponds to the function name field, not tag
     *     name field, defined in the Google Tag Manager web interface.
     * @param parameters An optional map of parameters as defined in the Google
     *     Tag Manager web interface.
     */
    - (void)execute:(NSString *)functionName parameters:(NSDictionary *)parameters {
    
      if ([functionName isEqualToString:kMyTagFunctionName]) {
        // Process accordingly.
      }
    }
    @end
  3. 다음에 구성된 태그 이름을 사용하여 함수 호출 태그 핸들러를 등록합니다. Google 태그 관리자 웹 인터페이스:
  4. //
    // MyAppDelegate.h
    //
    #import <UIKit/UIKit.h>
    
    @interface MyAppDelegate : UIResponder <UIApplicationDelegate>
    
    @end
    
    
    //
    // MyAppDelegate.m
    //
    #import "MyAppDelegate.h"
    #import "MyFunctionCallTagHandler.h"
    #import "TAGContainer.h"
    #import "TAGContainerOpener.h"
    #import "TAGManager.h"
    
    @implementation MyAppDelegate
    
    - (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
    
      // Open the container.
      id<TAGContainerFuture> future =
          [TAGContainerOpener openContainerWithId:@"GTM-XXXX"    // Placeholder Container ID.
                                       tagManager:[TAGManager instance]
                                         openType:kTAGOpenTypePreferNonDefault
                                          timeout:nil];
    
      // Method calls that don't need the container.
    
      self.container = [future get];
    
      // Register a function call tag handler using the function name of the tag as
      // defined in the Google Tag Manager web interface.
      [self.container registerFunctionCallTagHandler:[[MyFunctionCallTagHandler alloc] init]
                                              forTag:kMyTagFunctionName];
    }
    @end

커스텀 새로고침 기간 설정

Google 태그 관리자 SDK는 현재 컨테이너 사용 기간이 12시간을 초과하면 새 컨테이너가 설정 커스텀 컨테이너 새로고침 기간을 늘리기 위해 NSTimer: 다음 예를 참고하세요.

- (void)refreshContainer:(NSTimer *)timer {
  [self.container refresh];
}

self.refreshTimer = [NSTimer scheduledTimerWithTimeInterval:<refresh_interval>
                                                     target:self
                                                   selector:@selector(refreshContainer:)
                                                   userInfo:nil
                                                    repeats:YES];

로거로 디버깅

Google 태그 관리자 SDK는 기본적으로 오류 및 경고를 로그에 출력합니다. 더 자세한 로깅을 사용 설정하면 디버깅에 도움이 될 수 있으며 다음 예와 같이 자체 Logger를 구현합니다.

// MyAppDelegate.h
// This example assumes this file is using ARC.
// This Logger class will print out not just errors and warnings (as the default
// logger does), but also info, debug, and verbose messages.
@interface MyLogger: NSObject<TAGLogger>
@end

@implementation MyLogger
- (void)error:(NSString *)message {
  NSLog(@"Error: %@", message);
}

- (void)warning:(NSString *)message {
  NSLog(@"Warning: %@", message);
}

- (void)info:(NSString *)message {
  NSLog(@"Info: %@", message);
}

- (void)debug:(NSString *)message {
  NSLog(@"Debug: %@", message);
}

- (void)verbose:(NSString *)message {
  NSLog(@"Verbose: %@", message);
}
@end

// MyAppDelegate.m
// This example assumes this file is using ARC.
@implementation MyAppDelegate

- (BOOL)application:(UIApplication *)application didFinishLaunchingWithOptions:(NSDictionary *)launchOptions {
  self.tagManager = [TAGManager instance];
  
  self.tagManager.logger = [[MyLogger alloc] init];
  
  // Rest of Tag Manager and method implementation.
  return YES;
}
// Rest of app delegate implementation.
@end

또는 TagManager::logger::setLogLevel, 예를 들면 다음과 같습니다.

// Change the LogLevel to INFO to enable logging at INFO and higher levels.
self.tagManager = [TAGManager instance];
[self.tagManager.logger setLogLevel:kTAGLoggerLogLevelInfo];